If an element is removed from the page, does it automatically unbind? Or is this a scenario in which one ought to unbind using jquery's unbind?
I assume it's done automatically...
If you remove elements using remove
or empty
, event handlers will automatically be removed in order to prevent memory leaks. Otherwise they will remain, unless they are explicitly unbinded prior to removing those elements.
EDIT: Turns out .html
will remove event handlers too, by calling an internal .cleanData
method (declared on line 5177). You can check this in the source:
html: function( value ) {
...
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
...
So, to avoid memory leaks, don't directly use innerHTML
to replace DOM elements which have attached jQuery event handlers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With