Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery : Are events handlers removed from objects if they are removed from the DOM using html()

I am concerned about memory leaks in my application as I use jquery's html() method a lot to replace content in the the DOM. I just want to make sure that not of these event listeners are going to be hanging around in browser memory.

I have searched the jquery docs with no clear answer. Does anyone know?

Thanks guys!

like image 887
wilsonpage Avatar asked Apr 01 '11 10:04

wilsonpage


2 Answers

Yes they are.

If you use jQuerys .html() it will take care of you. Looking into the jQuery source, this line is getting called:

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

which effectively cleans up all data and events. This of course won't work if you're overwritting a DOMnodes innerHTML property explicitly.

like image 166
jAndy Avatar answered Nov 16 '22 02:11

jAndy


It seems using bind in jQuery, you can have more control over the 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 that is possible to control with the normal jQuery syntax of $('a').click() since all that is returned is a jQuery object and no references to the handlers or events.

There is related discussion to this question here on stack overflow:

javascript memory leaks

like image 45
Tom Gruner Avatar answered Nov 16 '22 02:11

Tom Gruner