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
and so on. It's odd to me that alert('hello') wouldn't also accumulate.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With