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