Trevor
Trevor

Reputation: 2457

jQuery unbind not working properly

Trying to Unbind a function when it is clicked and then rebind it after it is finished loading. So far bind works. But unbind does nothing. Here are different functions that I've tried. So far none work.

function disableswitch(){
 $('.profilebutton').unbind("click", function(){
  profilebuttonswitch(this.value);
 });
}
function disableswitch(){
 $('.profilebutton').unbind("click", function(){
   profilebuttonswitch();
 });
}
function disableswitch(){
 $('.profilebutton').unbind("click", profilebuttonswitch);
}

Anybody know why these might not be working for me?

Upvotes: 0

Views: 71

Answers (2)

Alnitak
Alnitak

Reputation: 339786

Only the third of your attempts might work.

When you .unbind (or in later jQuery versions .off) a handler you must supply either no function parameter at all, or you must supply the exact same function reference as was passed to .bind (or .on).

Passing a reference to a function that happens to look the same doesn't work because it won't have the same reference.

Upvotes: 2

myfunkyside
myfunkyside

Reputation: 3950

You have to reference a previously bound function using this format:

$( "#foo" ).bind( "click", handler );
$( "#foo" ).unbind( "click", handler );

Quote from http://api.jquery.com/unbind/:

$( "#foo" ).bind( "click", function() {
  alert( "The quick brown fox jumps over the lazy dog." );
});

// Will NOT work
$( "#foo" ).unbind( "click", function() {
  alert( "The quick brown fox jumps over the lazy dog." );
});

Even though the two functions are identical in content, they are created separately and so JavaScript is free to keep them as distinct function objects. To unbind a particular handler, we need a reference to that function and not a different one that happens to do the same thing.

Upvotes: 1

Related Questions