Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbind jQuery ajaxSuccess event

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!

like image 945
Bob Smith Avatar asked Oct 22 '12 21:10

Bob Smith


1 Answers

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 ajaxSuccess to a function named hook:

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

And then change hook and try to unbind it:

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. Instead, unbind before you change the value of 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:

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

Of course, if you have another handler bound to document.ajaxSuccess, it will also be unbound.

like image 130
gilly3 Avatar answered Sep 19 '22 00:09

gilly3