Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On jquery, closures, and possible memory leaks

I've read quite a bit about how memory leaks are created in various versions of IE. Some great information can be found here:

http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx

http://laurens.vd.oever.nl/weblog/items2005/closures/

Using closures with JQuery is a very common practice. I can't find any articles at all that speak to JQuery's event model (where closures are heavily used) with regards to IE and memory leaks In the second article posted above is a strategy to avoid memory leaks when using closures.

Does JQuery already implement a strategy similar to the one outlined in the article with regards to helping clean up potential leaks when using closures? Or is that something I must be aware of and code for?

For example,

Creates a memory leak in IE6/7:

function foo(value) {   
    var bar = document.getElementById("selector");
    bar.attachEvent("onclick", 
        // closure
        function() {
            alert(value); // reference to 'value' from outer function scope   
        }
    ); 
}

does the following JQuery version of the above example cause a memory leak in IE6/7?

function foo(value) {   
    $('#selector').click(
        // closure
        function() {
            alert(value); // reference to 'value' from outer function scope   
        }
    ); 
}
like image 343
Erik Avatar asked Oct 14 '22 14:10

Erik


1 Answers

from jQuery 1.3 source:

remove: function( selector ) {
    if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
        // Prevent memory leaks
        jQuery( "*", this ).add([this]).each(function(){
            jQuery.event.remove(this);
            jQuery.removeData(this);
        });
        if (this.parentNode)
            this.parentNode.removeChild( this );
    }
},

as you can see, it removes all event handlers and related data before removing an element and it's subelements.

like image 170
Javier Avatar answered Oct 27 '22 07:10

Javier