Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - Why use removeEventListener vs just deleting it?

I'm learning JavaScript and the methods to interact with the DOM.

I got to event listeners and saw that there is a removeEventListener() method.

I understood how to use it but was curious as to why we don't just delete the line of code with the event listener we don't want? Is there a reason as to why it is better to use the remove method over just removing ourselves?

Any clarification on this would be helpful :)

Thanks

question from:https://stackoverflow.com/questions/66055514/why-use-removeeventlistener-vs-just-deleting-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might want to add a listener to an element, then remove the listener later. You don't want to remove the listener code entirely because then the listener won't fire during the interval you want it to.

const button = document.querySelector('button');
button.addEventListener('click', () => {
  const listener = () => console.log('hovered');
  button.addEventListener('mouseover', listener);
  setTimeout(() => {
    console.log('listener removed');
    button.removeEventListener('mouseover', listener);
  }, 2000);
});
<button>click to enable hover listener</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...