Search code examples
jquerymemory-leaksunbind

How to correctly unbind dom-elements in jQuery widgets?


I have some troubles with memory leaks in JavaScript.

I'm using the Leak Memory 0.4.5 extension for Firefox which shows me those JavaScript objects which still remain in the memory.

Now I'm not sure how to correctly unbind dom-object from events etc.

For instance, I have a jQuery-widget called 'dropdownbox'. In the destroy method I make all the necessary stuff to unbind event-handlers like:

this.box.find('.toggler').unbind();
this.box.remove();
this.box = null;

These 3 lines are a must, or is it possible to call only this.box.remove()?

Till today I never have unbound or cleared something from DOM elements because I thought it doesn't matter. But I came up with the problem, that after 2 hours of developing on the same site, my Firefox consumes 1GB!

So I read a bit of memory leaks when using closures etc.
So that's my second question: I use very often closures because they are really cool and handy.
Some people say that you shouldn't use closures for everything. so for example if we have the following code:

function foo(param1, param2) {
  var local1, local2;
  $('a').click(function() {
    alert('YEAH');
  });
}

It would be better to do it like:

funtion foo(param1, param2) {
      var local1, local2;
      $('a').click(clickEvent);
    }
function() {
  alert('YEAH');
}

Or have I misunderstood that?


Solution

  • You can just call:

    this.box.remove();
    this.box = null;
    

    .remove() will also remove any child elements and their event handlers/data as well. Nulling out the reference held by .box to the element is the last step for complete removal (assuming nothing else it hanging onto it).

    For your other example, the second version is a bit more efficient since the handler's not copied all over the place, the bigger that handler is the more it makes a difference.