Skip to content Skip to sidebar Skip to footer

Fire Event Written In Child View In Backbone.js

I am using backbone js. suppose i have a child view called 'childView' and a parent view called 'parentView'. parentView = Backbone.View.extend({ render: function () { new ch

Solution 1:

The simplest way is to use Backbone.View's instance. Backbone.View is mixed with Backbone.Events which give you possibility to use it as event aggregator.

Example for your case:

childView = Backbone.View.extend({
  render: function () {

  },
  events: {
    'click .abc' : 'fireEvent'
  }, 
  fireEvent: function (e) {
      this.trigger('child:event:fired', e);
  }
});

And in parent view:

parentView = Backbone.View.extend({
  render: function () {
    this.childView = newchildView();
    this.childView.on('child:event:fired', this.onChildEvent, this);
    childView .render();
  }, 
  onChildEvent: function (e) {
        console.log("child view event");
  },
  closeThisView: function () {
    this.childView.off('child:event:fired', this.onChildEvent, this);
  }
})

This way you can subscribe to childView events, but you need to manually manage unbinding from all subscriptions.


Another solution for the same issue can be found by declaring global event aggregator for both views.

var vent = _.extend({}, Backbone.Events);

And in your views just trigger needed events with vent.trigger and subscribe/unsubscribe with vent.(on/off) methods.

Post a Comment for "Fire Event Written In Child View In Backbone.js"