Open ahmarcode opened 1 year ago
The "removal" of event handlers was to me, crazy in JS. The comment above is a bad way to solve accumulation of event listeners, but it worked.
But there's a proper solution using AbortController
.
https://stackoverflow.com/a/70498530/11392807 - added to WHATWG in 2020
const eventCleanupGuy = new AbortController();
// somewhere at a top level is fine too, this guy can do multiple rounds of aborts
ctaNode.addEventListener ('click', (e) => {}, { signal: eventCleanupGuy.signal });
ctaNode2.addEventListener('click', (e) => {}, { signal: eventCleanupGuy.signal });
// when you want to clean up those event handlers
eventCleanupGuy.abort();
OK, to properly add/remove listeners, avoid using lambas. Create a function or arrow function and keep the reference around. See - 2 mins.
So, it's not that crazy.