fire event written in child view in backbone.js

血红的双手。 提交于 2019-12-12 02:55:11

问题


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.



来源:https://stackoverflow.com/questions/27314230/fire-event-written-in-child-view-in-backbone-js

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