Question

I have a simple view which renders set of images depending on given items array (simplified code), using this as I need to collect some other data to 'build' required class name(s):

App.MyView = Ember.View.extend({
    buildTemplate: function () {
        var itemz = this.get('items');
        var classname = 'classNameDependingOnSomeCalculations...';
        var out = '<div>';
        $.each(itemz, function (index, obj) {
            out += '<img {{action myActionHere}} src="' + obj.href + '" alt="" class="'+classname+'"/>';
        });
        out += '</div>';
        return out;
    }.property('view'),
    defaultTemplate: Ember.Handlebars.compile(
        "<div>{{{view.buildTemplate}}}</div>"
    )
});

And in template I'm using it as

{{#each myObj in myCollection}}
    {{view App.MyView  itemsBinding="myObj.items" otherBinding="otherProps" }}
{{/view}}

Unfortunately this way Ember instead of binding the action puts {{action myActionHere}} directly into code...

How can I bind an action instead while building dynamic template?

I'm using Ember 1.1.2

P.S. Or maybe I should use quite other approach for building this view?

Was it helpful?

Solution

There is a workaround to make this work with the view as you've laid it out here... But this is really not the ember way of doing it. If for some reason you need this kind of an approach, I'll append an answer for that, but I'm going to aim to fix the underlying issue.

Instead of doing this as shown here, you should instead have code that looks like the following directly in your JSP:

{{#each myObj in myCollection}}
    <div>
    {{#each item in myObj.items}}
        <img {{action myActionHere}} src={{item.href}} alt='' class={{classNameFunction}}/>
    {{/each}}
    </div>
{{/each}}

If your reason for wanting to do this as a view is so that you can reuse this functionality without rewriting the code, take a look at partials which are specifically designed for that purpose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top