开发者

jQuery unbind behaviour after function runs

I have a toolbar that manipulates a Google map. Some of the functions affect markers placed on the map. I have a reset button that clears the changes and returns the map to the original state.

I need to "disable" the reset button until the map is changed. So...

  1. When an action is completed that manipulates the map, I bind the ResetMap() function to the reset button.
  2. Reset button is clicked and returns the map to original state.
  3. Reset button action is unbound again.

However, I can't get step 3 to work. I tried to unbind the event at the end of the ResetMap() function like so:

function ResetMap(){
 var Wrapper = $("#page_layout").find("#InlineToolbarMessages");
 if(Wrapper.hasClass('isExpanded')){
  Wrapper.removeClass('isExpanded');
  Wrapper.addClass('isCollapsed');
 }
 $开发者_开发知识库("#page_layout").find('#NumSelectedNumber').html("0");
 $("#page_layout").find('div#SelectedVoters').html("");
 clearMarkers();
 $('#page_layout').find('#reset_button').unbind('click', function(){
  ResetMap();
 });
}

I also tried a more global:

$('#page_layout').find('#reset_button').unbind();

without success. What am I doing wrong?


Edit: Based on your comment that you "...found out that if [you] did $('#reset_button').unbind('click'); before [you] called the `ClearMarkers()`` function that it worked. Similarly in another function for a different button, [you] put the unbind at the beginning and it worked.":

That makes me think that either A) The code earlier is throwing an exception, preventing your getting to the unbind call at all, or B) The code earlier is removing the reset_button button or adding another one with the same ID (which will make the document invalid and the behavior of an ID selector indeterminate).


Original Answer

Change

$('#page_layout').find('#reset_button').unbind('click', function(){
    ResetMap();
});

to

$('#page_layout').find('#reset_button').unbind('click', ResetMap);

...assuming you used ResetMap in the bind call. Since you haven't shown the bind, it's hard to say for certain.

When you call unbind with a function reference, it has to be the exact same function reference that you gave bind (or one of bind's shortcuts, click and such).

So for instance, this works:

// Binding
$("#myElement").bind("click", myFunction);

// Unbinding
$("#myElement").unbind("click", myFunction);

...but this does not work:

// Binding
$("#myElement").bind("click", function() {
    myFunction();
});

// Unbinding
$("#myElement").unbind("click", function() { // <== Does not work
    myFunction();
});

...because the function references are not the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜