Removing a DOM element also removes your listening?

6

I already know about the Dirt Collector feature.

My question is regarding this resource for addEventListener .

Example

test.addEventListener('mouseover', function(){
  test.className = 'active';
});

test.addEventListener('mouseout', function(){
  test.className = '';
});

var i =0; setInterval(function(){
  count.innerHTML = ++i;
}, 1000);

setTimeout(function(){
  test.remove();
}, 5000);
#test{
  width:100px;
  height:50px;
  background : #0000FF;
}

#test.active{
  background : #00FF00;
}
<span id="count">0</span>

<div id="test">
</div>

Question

  • When doing .remove() what happens to the listener? does it get a null reference?
  • Before simply removing the element do I need to removeEventListener ? or will the GC catch the listen?
asked by anonymous 29.10.2017 / 14:58

1 answer

4

Remove from the DOM by itself does not remove the event headphones. An example of this is that we can keep a reference to the element:

const inicio = new Date();
const test = document.getElementById('test');
test.addEventListener('click', function(segs) {
  const agora = new Date();

  console.log('clique! passados', Math.round((agora - inicio) / 1000), 'segundos');
});

test.remove();
console.log(test.parentElement);
test.click();
setTimeout(() => test.click(), 10000);
#test {
  width: 100px;
  height: 50px;
  background: #0000FF;
}

#test.active {
  background: #00FF00;
}
<span id="count">0</span>

<div id="test">
</div>

When a few years SPA (single page aplication) began to be popular and moving around a lot in the DOM without refresh of the page problems of memory leaks arose. Some of these leaks were because removing an element from the DOM does not release everything that was associated with the element.

You must also remove the event headphones by passing the same function to the removeEventListener method.

In your example this would be:

const test = document.getElementById('test');
const adicionarClasse = function() {
  this.className = 'active';
}
const removerClasse = function() {
  this.className = '';
}
test.addEventListener('mouseover', adicionarClasse);
test.addEventListener('mouseout', removerClasse);

setTimeout(function() {
  test.removeEventListener('mouseover', adicionarClasse);
  test.removeEventListener('mouseout', removerClasse);
  test.remove();
}, 5000);
#test {
  width: 100px;
  height: 50px;
  background: #0000FF;
}

#test.active {
  background: #00FF00;
}
<div id="test">
</div>

Related: an MDN article on memory leaks ( in English )

    
29.10.2017 / 15:10