如何在骨干中的另一个视图中绑定元素上的事件

时间:2013-03-14 04:34:56

标签: backbone.js binding views underscore.js models

我正在尝试附加事件来自另一个视图

我有两个观点

  • headerView
  • 内容查看

我的headerView使用Header模型,每次模型更改时,我都会渲染()我的headerView。

与大多数iPhone的应用程序一样,我在标题中使用两个按钮进行导航,具体取决于您的位置,图像可以更改。

这就是为什么当我初始化随机contentView时,我可以访问headerView中的模型并更改属性。

我需要做的最后一件事是为这个按钮创建一个点击事件。

我正在尝试在我的内容视图中绑定(这更有意义)

events: {
   "click .h_left": "newLocation",
}

事件没有触发,只有我将这个事件放在headerView中才会出现这种情况,是否有推荐的干净解决方案呢?

1 个答案:

答案 0 :(得分:10)

Backbone.View的重点是将DOM子树的修改和事件处理封装到View类中。因此,Backbone不支持您的方案。

您可以通过几种方法获得相同的最终结果。

简单(但错误)方式:使用jQuery监听标题的事件:

var ContentView = Backbone.View.extend({
   initialize: function() {
     $(".h_left").on('click', this.newLocation);
   },

   remove: function() {
     $(".h_left").off('click', this.newLocation);
     Backbone.View.prototype.remove.call(this);
   }
});

这打破了header元素的封装,并将内容视图紧密耦合到header元素的实现。换句话说:意大利面。

正确方法:使用中介将邮件中的邮件传递到其他视图:

var HeaderView = Backbone.View.extend({
  events: {
    "click .h_left": "onLeftButtonClick"
  },

  onLeftButtonClick: function() {
    //You can use the root Backbone object as a global event bus
    //Publish a message
    Backbone.trigger('header:leftbutton');
  }
});

var ContentView = Backbone.View.extend({
   initialize: function() {
     //Subscribe to a message. If you use listenTo, the subscription is 
     //automatically cleared when your content view is destroyed.
     this.listenTo(Backbone, 'header:leftbutton', this.newLocation);
   },

   newLocation: function() {
     //..
   }
});
相关问题