Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript event handler after removing node

Tags:

javascript

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.

like image 910
abdul raziq Avatar asked Oct 03 '22 20:10

abdul raziq


1 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.

like image 148
slebetman Avatar answered Oct 13 '22 12:10

slebetman