Search code examples
backbone.jsrequirejs

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


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


Solution

  • 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);
    }