简体   繁体   English

取消绑定jQuery ajaxSuccess事件

[英]Unbind jQuery ajaxSuccess event

Having trouble unbinding a global ajaxSuccess event handler. 无法解除全局ajaxSuccess事件处理程序的绑定。

Every time I run the following code and then test an ajax function the method hook is called once for each time I ran the code. 每次运行以下代码然后测试ajax函数时,每次运行代码时都会调用一次方法钩子。

var hook = function() { console.log('hey'); };
$(document).unbind('ajaxSuccess', hook); // not working
$(document).bind('ajaxSuccess', hook);

I've also tried just using 我也尝试过使用

$(document).ajaxSuccess(hook);

but the above doesn't replace the existing reference to hook and has the same behaviour as above. 但是上面的内容并没有取代现有的钩子引用,并且具有与上面相同的行为。

One thing that may be relevant is that I'm using a very old version of jQuery (1.3.2). 可能相关的一件事是我使用的是非常旧版本的jQuery(1.3.2)。

I'm sure there is an obviously solution I'm missing here, but the brain just isn't working today. 我确信这里有一个显而易见的解决方案,但是大脑今天没有用。 Any help will be greatly appreciated! 任何帮助将不胜感激!

Thanks in advance! 提前致谢!

The second argument in .unbind() should be a reference to the function that is currently bound. .unbind()的第二个参数应该是对当前绑定的函数的引用。 If you change the variable to point to a different function, it won't work. 如果将变量更改为指向其他功能,则无效。

So, if you first bind ajaxSuccess to a function named hook : 因此,如果您首先将ajaxSuccess绑定到名为hook的函数:

var hook = function () { console.log("a"); };
$(document).bind("ajaxSuccess", hook);

And then change hook and try to unbind it: 然后更改hook并尝试解除绑定:

hook = function () { console.log("b"); };
$(document).unbind("ajaxSuccess", hook);
$(document).bind("ajaxSuccess", hook);

This will fail because hook no longer contains a reference to the original function. 这将失败,因为hook不再包含对原始函数的引用。 Instead, unbind before you change the value of hook : 相反,在更改hook的值之前取消绑定:

$(document).unbind("ajaxSuccess", hook);
hook = function () { console.log("b"); };
$(document).bind("ajaxSuccess", hook);

Or, if that's not possible, eg, because the original hook is no longer in scope, you can omit the second parameter to remove all bound handlers: 或者,如果这不可能,例如,因为原始hook不再在范围内,您可以省略第二个参数以删除所有绑定处理程序:

$(document).unbind("ajaxSuccess");

Of course, if you have another handler bound to document.ajaxSuccess , it will also be unbound. 当然,如果你有另一个绑定到document.ajaxSuccess处理程序,它也将是未绑定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM