我已经使用 Backbone 工作了几天,阅读了有关设计模式的内容以及您有什么。在阅读了一堆资源之后,今天我搞乱了 subview 。主要是这两个帖子-
德里克·贝利
http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
伊恩·斯托姆·泰勒
http://ianstormtaylor.com/assigning-backbone-subviews-made-even-cleaner/
这些和其他对于帮助我设置一些 subview 并以我认为正确的模式处理它们的关闭非常有用:
Backbone.View.prototype.close = function(){
var ctx = this;
_.each(ctx.subViews(), function(view) {
view.close();
});
this.remove();
this.unbind();
}
这里没有问题,似乎符合我的预期。但我想测试一下,看看发生了什么。所以我停止在 subViews 上调用 close 并循环我的渲染 20,000 次:
Backbone.View.prototype.close = function(){
var ctx = this;
_.each(ctx.subViews(), function(view) {
//view.close();
});
this.remove();
this.unbind();
}
这里没有僵尸事件处理程序或 DOM 节点。这让我有点惊讶——我不是 jQuery 内部专家,我希望至少仍然有来自子节点的事件处理程序。但我猜是因为我的 subview 都包含在父 View 中,父 View 仍在被删除和解除绑定(bind),所以 jQuery 可以很好地清除所有 subview 。所以我停止解除父元素的绑定(bind):
Backbone.View.prototype.close = function(){
var ctx = this;
_.each(ctx.subViews(), function(view) {
//view.close();
});
this.remove();
//this.unbind();
}
我在 Chrome 检查器中的事件处理程序计数仍然没有增加。
所以我的问题是:
当您需要以这种方式巧妙地处理事件解除绑定(bind)和 subview 时,什么是“真实”示例?它是否在您的 View 的直接范围之外的任何对象引用?是否仅当您的 subview 不包含在父 View 的 $el 中时?
最佳答案
当您从 DOM 中删除父 View 时,jQuery 会清除所有与 subview 相关的 DOM 事件。 unbind()
是 Backbone 的 Events.off
的别名,它会删除您可能使用 myChildView.on('someEvent', ... )
。例如,父 View 可能会监听您在 subview 中触发的事件。如果这样做,则需要调用 this.unbind()
或 this.off()
。
现在 Backbone.Events(自 0.9.9 起)具有 listenTo()
和 stopListening()
,您可以考虑添加 this.stopListening()
到您的 close()
。然后,如果在您看来,您使用了类似 this.listenTo(this.model, ...)
的东西,它们也会被正确清理。
关于javascript - Backbone subview 和事件解除绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614744/