Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

if i add event handler on any element in javascript like

var link = document.createElement("a");

document.body.appendChild(link);


link.addEventListner("click",function(){

     alert("do something");

});

and then i remove the link

link.parrentNode.removeChild(link);

then what about event that i attached to link will it also be removed or will it remain in memory (a bit confused with how event are stored in memory and for how long) or should i first remove the the event handler and then i remove the link node.

share|improve this question
    
You don't attach events, you attach a listener for an event (hence the name of the method). The listener exists only as long as the object (DOM element) it's attached to exists. –  RobG Sep 26 '13 at 5:30
add comment

2 Answers

Almost all browsers will remove the event handler from memory when the garbage collector is invoked. However, IE6 and below has a known bug that may cause the event handler not be garbage collected causing the page to leak memory.

It used to be considered good practice to clean up event handlers before removing an element (indeed, libraries like YUI and JQuery have functions for this). But these days I'd say only worry about this if you care about IE6.


Note: in case you're wondering about the bug. It's due to the fact that IE's garbage collector could not handle circular references if it involves the DOM (on older IE it couldn't handle circular references even if it didn't involve the DOM).

So for example, if you have code like this:

myDiv.onclick = function () { myDiv.style.backgroundColor = 'red' }
//                               ^
//                               |
//                     circular reference

then IE6 and below couldn't free the event handler. But if your event handler does not contain any circular reference back to the DOM object it's attached to then IE will garbage collect it.

share|improve this answer
    
Link to a related question: stackoverflow.com/questions/10092619/… –  slebetman Sep 26 '13 at 5:20
    
IE 6 and 7 don't support addEventListener anyway, so in this case they will just throw an error. ;-) –  RobG Sep 26 '13 at 5:34
add comment

In javascript function expressions(in your case event binding) allocate an object and hence consumes the memory. You should remove or handle it properly. Check this link which explains memory management in detail.

Js Memory Management

Check Garbage collection section.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.