SO-71409116-ray-hatfield-answer-response-1
The original answer attempt does not accurately reproduce the Stack Overflow issue
by avwon
HTML
<button>Add Listener</button>
<div class="clickable">Clickable</div>
CSS
.clickable {
padding: 4rem;
text-align: center;
background: skyblue;
max-width: 150px;
margin: 0 auto;
}
JavaScript
const div = document.querySelector('div');
document.querySelector('button').addEventListener('click', () => {
// 03/09/2022 Avwon: This is a more accurate example of what is happening, even when creating multiple listeners the reference to the original handler is not lost within the arrow function and all of them are removed when clicking on the blue clickable
let handler = () => {
console.log('clicked');
div.removeEventListener('click', handler);
} // declares a new handler function
div.addEventListener('click', handler); // add the handler
})
/*
// THE ORIGINAL ANSWER ATTEMPT by SO @ray-hatfield 03/09/2022
const div = document.querySelector('div');
document.querySelector('button').addEventListener('click', () => {
let handler = () => console.log('clicked'); // declares a new handler function
div.removeEventListener('click', handler); // not removed because this new function isn't attached
div.addEventListener('click', handler); // add the handler
})
*/