How can I capture which events were deleted with unbind and reapply them later?

How can I save which events were deleted using unbind and reapply them later?

Suppose I have this element:

<div id="thediv">The Div</div> 

which has a different number of functions related to its onclick event. I know that I can use unbind to remove all onclick functions:

 $("#thediv").unbind("click"); 

How to save unrelated functions to re-link them later?

Note that this should work with jQuery 1.5.


I saw this previous answer , but there are a few things that I did not understand about this:

  • Why does it bind first and then untie?
  • What does ary_handlers[idx] do?

(I am not looking for answers to these questions, unless they are necessary to explain the solution to my question about capturing unrelated functions.)

+4
source share
1 answer

I think you could do something like this: you save the div events by cloning the div and storing the data (β€œevents”) in the object. Afterword you iterate over an object and bind events. You have to clone, because when you unbind events, the original data ("events") is deleted (I hope I understand what you are looking for)

 <div id='my'>my</div> var my = $('#my'); my.click(function(){ alert('my'); }); my.hover(function(){ $(this).css('color', 'red'); }); my.click(function(){ alert('you'); }); var ev =my.clone(true).data('events'); my.unbind(); for (var e in ev){ //you have to iterate on the property since is an array with all the handlers for the same event) for (i= 0; i < ev[e].length; i++){ my.bind(e, ev[e][i]); } } 

fidlle http://jsfiddle.net/pXAXW/

EDIT. To do this work in 1.5.2, you just need to change the way events are bound, because they are saved in different ways:

  $(document).ready(function(){ var theDiv = $("#thediv"); theDiv.click(function(){ $(this).css("border-color", "blue"); alert("Click!"); }); theDiv.click(function(){ $(this).css("border-color", "blue"); alert("clack!"); }); var theEvents = theDiv.clone(true).data("events"); // Unbind events from the target div theDiv.unbind("click"); // Put the saved events back on the target div for (var e in theEvents){ // must iterate through since it an array full of event handlers for ( i=0; i<theEvents[e].length; i++ ){ theDiv.bind(e, theEvents[e][i].handler); } } }); 

fiddle here: (just like Katiek) http://jsfiddle.net/nicolapeluchetti/CruMx/2/ (the event fires twice if you don’t click on the div!) I also updated my script to use jquery 1.5. 2 http://jsfiddle.net/pXAXW/1/ )

+3
source

All Articles