Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does using addEventListener accumulate in Javascript?

I already saw this question on SO: JavaScript: remove event listener

I understand what it does. But I don't know why addEventListener will sometimes accumulate overtime whereas other times it doesn't.

My understanding from toying with my code is that accumulation only happens when there is addEventListeners nested in another addEventListener? Could someone explain why this happens?

http://jsfiddle.net/dTx72/1/

In my demo above, I just have a div with a button inside. I have added an addEventListener to the div and to the button. When the button is clicked, an alert pops up.

<div id='clickBox'>
  <button id='button'>Click Me</button>
</div> 

Javascript

 document.getElementById('clickBox').addEventListener('click', function () {
    alert('hello');
    document.getElementById('button').addEventListener('click', function () {
      alert('accumulates per click');
    });
 });

The result is

  • First click: alert('hello'), alert('accumulates per click'),
  • Second click: alert('hello'), alert('accumulates per click'),alert('accumulates per click')

and so on. It's odd to me that alert('hello') wouldn't also accumulate.

like image 328
user3850688 Avatar asked Oct 22 '25 14:10

user3850688


1 Answers

addEventListener is always accumulative. As its name says, it adds an event listener, but doesn't remove previous ones.

However, if you add the same function as an event listener for same event in same phase, that function will only run once.

Examples:

el1.addEventListener('click', f);
el1.addEventListener('click', g);
el1.click(); // f and g run once

el2.addEventListener('click', f);
el2.addEventListener('click', f);
el2.click(); // f runs once

el3.addEventListener('click', f, true);
el3.addEventListener('click', f, false);
el3.click(); // f runs twice (one during capture and one during bubbling)

el4.addEventListener('click', function(){ alert('a'); }, true);
el4.addEventListener('click', function(){ alert('a'); }, false);
el4.click(); // The function will run twice, because even if they do the same,
             // they are different functions
like image 177
Oriol Avatar answered Oct 25 '25 05:10

Oriol