Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbinding in jQuery

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...

like image 588
Matrym Avatar asked Dec 05 '10 00:12

Matrym


1 Answers

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.

like image 114
karim79 Avatar answered Nov 04 '22 01:11

karim79