How to trigger an event from child view to parent view in backbonejs and requirejs

余生长醉 提交于 2019-12-11 02:26:53

问题


I have a parentview which dynamically creates a child view and I have triggered an event from child view to parent view and I am passing the model of the child view to parent view with some properties set. now in the parent view i have to take the model and add to collection. here is my code child view trigger code

$(this.el).trigger('added', this.model);

parentview event

events: {
            "added": "addNewAttribute"
        },
    addNewAttribute: function (model) {
        console.log(model);
        this.collection.add(model);
        console.log(this.collection);
    }

console.log returns undefined. can someone let me know how to pass the model back to parent view?

thanks


回答1:


I may be off base but I'd guess that the child view did not do binding for the function that contains this code:

$(this.el).trigger('added', this.model);

As a result when you get into the function that code is in, "this" doesn't point to the child view, it points to some DOM object or something. Then this.model doesn't point to what you expect.

For example:

initialize : function () {
  _.bindAll(this, "addFunction");
}

addFunction : function () {
  $(this.el).trigger('added', this.model);
}



回答2:


Just faced the same problem!

The thing is that the parent function takes as first parameter the event and the trigger function passes variables as an array. so the code should be like:

$(this.el).trigger('added', [this.model]);

parentview event:

events: {
    "added": "addNewAttribute"
},
addNewAttribute: function (event,model) {
    console.log(model);
    this.collection.add(model);
    console.log(this.collection);
}

this worked for me.



来源:https://stackoverflow.com/questions/11056001/how-to-trigger-an-event-from-child-view-to-parent-view-in-backbonejs-and-require

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!