sanjar-notes / web_dev_fundamentals

The basics - HTML, CSS, Javascript and more
https://sanjar-notes.github.io/web_dev_fundamentals/
3 stars 0 forks source link

Replace all click listeners and add new, removing event listeners #88

Open ahmarcode opened 1 year ago

ahmarcode commented 1 year ago
// context
const onClickHandler = () => {};
const node = document.querySelector(/** some code */);

// Remove existing click listeners on node
const newNode = node.cloneNode(true);
node.parentNode.replaceChild(newNode, node);

// Attach the onClickHandler
newNode.addEventListener("click", onClickHandler);
sanjarcode commented 9 months 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();
sanjarcode commented 1 month ago

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.