Backbone Js:在单独的视图上聆听按钮点击

时间:2013-08-09 15:26:45

标签: javascript jquery backbone.js

我有一个父视图(View.A)来管理子视图View.B和View.C. View.B有一个控制View.B上的事件的按钮界面。

设置

View.A
  View.B
    view.B.template.html
  View.C
    view.C.template.html

View.B.template.html

<div class="btn-group">
  <button id="button-1" type="button" class="btn btn-default">
    Button 1
  </button>
  <button id="button-2" type="button" class="btn btn-default">
    Button 2
  </button>
</div>

查看.B视图

var View.B = Backbone.View.extend({
  template: _.template( view.B.template.html ),
  events: {
    'click #button-1': 'someMethod',
    'click #button-2': 'anotherMethod'
  },
  ...
})

我想要做的是使用View.B按钮控制View.C上的事件。我试图将delegatedEvents添加到View.C,以监听View.B模板中按钮ID的点击,但这不起作用。有解决办法吗?

1 个答案:

答案 0 :(得分:3)

我会创建一个eventaggregator,类似于:

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

然后你可以听取并触发事件。所以你会有这样的事情:

// This would be from View.B
someMethod: function(ev) {
    vent.trigger('someMethod', ev);
}

// And this would be in View.C
initialize: function() {
    this.listenTo(vent, 'someMethod', this.mySomeMethod);
}

然后,您可以在必要时重用事件聚合器。 MarionetteJS这样做。

相关问题