JQuery: event handlers are removed from objects if they are removed from the DOM using html ()

I am worried about a memory leak in my application, as I often use the jquery html () method to replace content in the DOM. I just want to make sure that not in these event listeners will hang in the browser memory.

I was looking for jquery docs with no clear answer. Somebody knows?

Thanks guys!

+8
jquery events memory
source share
2 answers

Yes they are.

If you use jQuerys .html() , it will take care of you. Looking into the jQuery source, this line gets a call:

 jQuery.cleanData( this[i].getElementsByTagName("*") ); 

which effectively clears all data and events. This, of course, will not work if you explicitly use the DOMnodes innerHTML property.

+5
source share

It seems that with bind in jQuery you can have more control over events and handlers, such as in this example, from http://api.jquery.com/unbind/

 var myHandlers = {}; myHandlers.handler = function() { alert('The quick brown fox jumps over the lazy dog.'); }; $('#foo').bind('click', handler); $('#foo').unbind('click', handler); delete(myHandlers.handler); 

But I don't know if it is possible to control using the standard jQuery syntax for $ ('a'). click (), since everything returned is a jQuery object and does not refer to handlers or events.

Stack overflow issues are discussed here:

javascript memory leaks

+1
source share

All Articles