【发布时间】:2013-03-20 06:29:24
【问题描述】:
更新: 根据我的评论,我的问题是我有一个额外的模型,我正在传递给我没有解除绑定事件的视图。当我看到事件处理程序被触发时,我假设源来自 this.model 而不是 this.extra_model,因为我忘记了 this.extra_model 也被用于错误验证。
解决方案是添加以下内容:
MyView = Backbone.extend({
//...
//add method to override BaseView
cleanUp: function() {
this.extra_model.off(null, null, this);
BaseView.prototype.cleanUp.apply(this, arguments);
},
//...
});
感谢您查看问题,对于程序员的错误,我们深表歉意。
全部: 在我清理视图后,我遇到过时/僵尸事件仍然被绑定的问题。当我将自定义事件绑定到模型时,问题就来了。当我从 dom 中删除视图时,我调用 'this.model.off(null, null, this);'正如各种留言板上所建议的那样,但是尽管我可以看到在 chrome 调试器工具中删除了“custom-handler”回调,但我仍然注意到“custom-handler”的事件处理程序被调用的次数超过了它应该调用的次数(每个额外一个我清理后重新创建视图的时间)触发事件时。有人能告诉我我的清理代码是否遗漏了什么吗?提前致谢!
BaseView = Backbone.extend({
//...
displayErrors:function(){},
cleanUp: function(){
if (this.model) this.model.off(null, null, this);
if (this.collection) this.collection.off(null, null, this);
if (!this.options.persistDataAfterViewCleanup) {
if (this.model) delete this.model;
if (this.collection) delete this.collection;
}
//_.each(this.subViews, function(view){view.cleanUp();}); not needed yet.
this.undelegateEvents();
$(this.el).removeData().unbind();
//Remove view from DOM
this.$el.html('');
this.remove();
}
});
MyView = BaseView.extend({
initialize: function(){
//called manually from model using trigger
this.model.on('custom-handler', this.displayErrors, this);
}
});
【问题讨论】:
-
原来是我自己的编程错误导致了这个问题。我在视图中使用了一个额外的模型,我必须在不同的路线上坚持,并且在调用清理之前我没有为该模型解除绑定事件。我通过在子视图中覆盖 cleanUp 来解决问题,取消绑定该额外模型的所有事件,然后调用 BaseView.prototype.cleanUp.apply(this, arguments);很抱歉垃圾邮件:(,感谢 fencliff 更新了 chrome 内存快照。我不知道你能做到这一点。