Selvaraj M A
Selvaraj M A

Reputation: 3136

How to bind event to dynamically created instance in ember.js

I have created a custom component which will contain reference to view(bound to a handlebar template). And my template has a button which I want to attach a click handler to it.

I will create the instance of my component dynamically and attach it to different divs. But my problem is how I can hook the view to the event handler which is defined in corresponding component instance.

    App.ImageView = Ember.View.extend({
        "templateName" : "image-template",
        "imagePath" : null,
        "controller" : null
    });

    App.ImageSwitcher = Ember.Object.extend({
        renderTo : null,
        init: function(){
            this.set("view",App.ImageView.create());
        }
        renderOnScreen: function(){
            this.get("view").appendTo(renderTo);
        }
        clickHandler : function(evt){
        }
    })

<script type="text/x-handlebars" data-template-name="image-template">
    <img {{bindAttr src="imagePath"}} />
    <input type="button" value="Change image" />
</script>

Component instance creation:

var component = App.ImageSwitcher.create({renderTo:"#div"});
component.renderOnScreen()


var component1 = App.ImageSwitcher.create({renderTo:"#div1"});
component1.renderOnScreen()

Now I want the buttons to invoke the clickHandler defined in corresponding App.ImageSwitcher instance. Is there any way to it. I tried to have a reference to the App.ImageSwitcher instance within the view. But it is not a clean way of doing it.

Upvotes: 1

Views: 1402

Answers (1)

Christopher Swasey
Christopher Swasey

Reputation: 10552

You can mixin Ember.TargetActionSupport into your view, and then have a click handler on that, as such:

App.ImageView = Ember.View.extend(Ember.TargetActionSupport, {
    templateName: "image-template",
    action: "clickHandler",
    imagePath: null,
    controller: null,
    click: function() {
         this.triggerAction();
    }
});

App.ImageSwitcher = Ember.Object.extend({
    renderTo : null,
    init: function(){
        this.set("view",App.ImageView.create({target: this));
    }
    renderOnScreen: function(){
        this.get("view").appendTo(renderTo);
    }
    clickHandler : function(evt){
    }
})

Upvotes: 3

Related Questions