【问题标题】:Backbone Cleanup - removing references of context bound callbacksBackbone Cleanup - 删除上下文绑定回调的引用
【发布时间】:2012-11-07 06:55:37
【问题描述】:

我正在开发一个 Backbone 应用程序。我创建了具有 destroy 方法的基本视图,所有其他视图都对其进行了扩展。

在销毁视图实例时,我想确保如果视图具有模型或集合,我将取消绑定它正在侦听的任何事件。

假设我在视图的初始化中使用下划线的 _.bindAll,是否会关闭 下面的语句删除引用。

var DocumentRow = Backbone.View.extend({

  initialize: function() {
      _.bindAll( this );

     this.model.on('change', this.render);
  },


  destroy : function() {
      // Will this work?
      this.model.off(null, null, this);

  }


});

或者我需要像这样显式绑定事件

this.model.on('change', this.render, this);

【问题讨论】:

  • 为什么将 null 传递给 model.off?
  • 移除视图中的所有回调。基于 Backbone 文档中的示例: // 删除所有事件的 context 的所有回调。 object.off(null, null, context);
  • 好的。我认为 this.model.on('change', this.render);应该可以正常工作,因为渲染将绑定到“this”,即您的 DocumentRow。

标签: javascript backbone.js underscore.js


【解决方案1】:

this.model.on('change', this.render); 不会按照你想要的方式工作。你需要改成this.model.on('change', this.render, this);

如果您查看 on 方法的源代码 (http://backbonejs.org/docs/backbone.html#section-18 ),它不会默认您的 context 变量为任何值。所以如果不设置,对off的调用将无法正确找到事件绑定。

FWIW,我厌倦了必须进行相应的 onoff 调用,所以我编写了一个插件来为我处理很多事情:https://github.com/marionettejs/backbone.eventbinder

您可以像这样使用它,而不必担心获得正确的上下文或其他任何事情。


var DocumentRow = Backbone.View.extend({

  initialize: function() {
     this.eb = new Backbone.EventBinder();
     this.eb.bindTo(this.model, 'change', this.render);
  },


  destroy : function() {
      this.eb.unbindAll();
  }

});

这样做的真正好处是不必为每个on 调用off。您只需调用一次unbindAll,它就会取消绑定存储在事件绑定器实例中的所有事件。

【讨论】:

  • 谢谢,我去看看eventBinder插件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
相关资源
最近更新 更多