views:

20

answers:

1

hi i have some troubles with memoryleaks in javascript. i'm using the Leak Memory 0.4.5 extension for firefox (https://addons.mozilla.org/de/firefox/addon/2490/) which shows me those javascript-objects which still remains 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-methode 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 unbined 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 teh same site, my firefox consumes 1GB! so i read a bit of memory leaks when using closures etc. so thats 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 everthing. so for example if we have the following code:

funtion 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 misunterstood that?

A: 

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.

Nick Craver
ok so i have to call $(window).unload(function() {$('temp').mywidget('destroy') }); to clean all correctly?
Davincho
@Davincho - You can, though most garbage collectors will cleanup when leaving the page (older IE you need to check but that's it). It's important to cleanup everything possible in your `destroy` function though, so any manual destroys are complete.
Nick Craver
that's the point: the garbage collector won't cleanup an object when we have circular references, so is there other posibility than call the destroy-method when the pages get unloaded?
Davincho
@Davincho - What circular references do you have? Event handlers and data aren't referenced by the DOM element, only it's `$.expando` property is there, not a direct reference, just a unique ID. If you can, you want to avoid creating circular references at all, like the jQuery event system does by default.
Nick Craver