jQuery.off() 和 jQuery.proxy()

标签 jquery

我正在使用 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/

相关文章:

javascript - Highcharts 柱形图用ajax动态更新

javascript - 我可以使用 javascript 原型(prototype)来制作点击动画吗?

javascript - 在正则表达式中使用变量 (jQuery)

javascript - 为什么所有迭代都同时运行?

jquery - 如何在 ASP.NET MVC 中使用 JQuery 调用 Controller 操作

javascript - jQuery 类型错误 : $ is undefined

jQuery:在所有空文本框中放置默认值

javascript - 使用 jquery 和 regex 设置正负十进制数的格式

javascript - 无法加载静态文件 express js

javascript - 使用 jQuery/javascript 显示服务器创建的图像