我正在使用 jQuery 1.7 中的新 on()
/off()
方法,并阅读我看到的 off()
文档下面这句话:
Handlers proxied by jQuery.proxy() or a similar mechanism will all have the same unique id (the proxy function), so passing proxied handlers to .off may remove more handlers than intended. In those situations it is better to attach and remove event handlers using namespaces.
这就是我面临的情况:
function show(){
this.$element.on( 'click', '.close', $.proxy(this.hide, this) );
}
function hide(){
this.$element.off( 'click', '.close', $.proxy(this.hide, this) );
}
如果我理解正确,对 $.proxy() 的所有调用都具有相同的 uid,因此我可能会解除附加比所需更多的处理程序...
如果这是正确的,我不明白(不知道)如何使用命名空间附加处理程序。
最佳答案
事件命名空间是捆绑一组相关事件的基本方法 - 例如,您可能希望在创建插件时使用命名空间,即:
$(document).bind('show.myplugin', function() {...});
$(document).bind('hide.myplugin', function() {...});
所以稍后,也许在销毁/拆卸时您可以执行以下操作:
$(document).unbind('.myplugin');
并且您定义的所有绑定(bind)都将被删除(使您无需单独删除每个绑定(bind))。
在您的情况下,这将允许您删除特定命名空间的事件,而无需删除命名空间之外的 $.proxy()
回调函数定义的其他绑定(bind)的事件。
关于jQuery.off() 和 jQuery.proxy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8714874/