Having trouble unbinding a global ajaxSuccess event handler.
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.
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).
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. If you change the variable to point to a different function, it won’t work.So, if you first bind
ajaxSuccessto a function namedhook:And then change
hookand try to unbind it:This will fail because
hookno longer contains a reference to the original function. Instead, unbind before you change the value ofhook:Or, if that’s not possible, eg, because the original
hookis no longer in scope, you can omit the second parameter to remove all bound handlers:Of course, if you have another handler bound to
document.ajaxSuccess, it will also be unbound.