views:

862

answers:

1

Hi,

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   
        }
    ); 
}
+4  A: 

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.

Javier
There is nothing in the question about calling of the .remove() method.
Edy Gomolyako
The well known leaking issue with IE comes up when you delete a DOM object that has event handlers, which can be a closure that holds a reference to this same DOM object. The solution is to remove all event handlers from the DOM object before removing it from the DOM tree. jQuery's .remove() method does exactly that.
Javier