views:

212

answers:

2

So, if in the javascript, I create a DOM object in the HTML page, and attach event listener to the DOM object, upon I remove the the DOM from HTML page, does the event listener still exist and causing memory leak?

  function myTest() {
     var obj = document.createElement('div');
     obj.addEventListener('click', function() {alert('whatever'); });
     var body = document.getElementById('body'); // assume there is a <div id='body'></div> already
     body.appendChild(obj);
  }

  // then after some user actions. I call this:
  function emptyPage() {
    var body = document.getElementById('body');
    body.innerHTML = '';  //empty it.
  }

So, the DOM object, <div> inside body is gone. But what about the eventlistener? I'm just afraid that it will cause memory leak.

A: 

JavaScript does garbage collection automatically for you.

It might free it right away or it might wait when the moment is best. This is up to the JavaScript implementation.

So no, it won't cause a memory leak.

Luca Matteis
Because I have problems with memory leaking in action script before. The situation is that the listener still alive when I remove the Flash embedded object from the DOM tree.That's why I am worrying about even removing the DOM from the HTML, the listender still alive...
seatoskyhk
+1  A: 

The sad thing is, the W3C does not have an events collection where you can sift through all events applied to a single element. You could do it manually (i.e. obj.Events = {}; obj.Events[type] = []; obj.Events[type].push(fn) for each event that is added. Event[types] is an array so if you have multiple functions you wish to fire at a time, you can remove each individually), then loop through the obj.Events object to remove all events before removing the object.

Akidi