fire event written in child view in backbone.js

2019-09-06 04:28发布

问题:

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 childView().render();
  }
})

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

  },
  events: {
    'click .abc' : 'fireEvent'
  }
})

I need to call click event written in childView in a parentView.

回答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 = new childView();
    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.