简体   繁体   中英

removeEventListener doesn't seems to work?

for some reason ,I need to delay click and preventDefault for some time when scroll page end.So I write something like this :

// const disableClickDuringScrollHandler=(e)=> {
//      e.preventDefault();
//    };
this.scrollHandler = e => {
  console.log('scrolling');
  const disableClickDuringScrollHandler = (e) => {
    e.preventDefault();
  };
  document.addEventListener('click', disableClickDuringScrollHandler);
  window.clearTimeout(this.scrollTimer);
  this.scrollTimer = window.setTimeout(() => {
    console.log('scroll end');
    document.removeEventListener('click', disableClickDuringScrollHandler);
  }, 300);
}
window.addEventListener('scroll', this.scrollHandler);

I also has been write a codepen: https://codepen.io/zhangolve/pen/gRNMoX

my question is when I put disableClickDuringScrollHandler outside of the scrollHandler ,removeEventListener can work well,but when I put disableClickDuringScrollHandler inside of the scrollHandler ,removeEventListener doesn't seem to work .

I have tried so many times to found why but failed.So I get here to ask your help.

The problem is that each time the user scrolls, you create a new disableClicksDuringScroll closure and add it as a click listener. When this timer runs, it removes the latest click listener, but not the previous ones (because they're different closures, so they aren't equal to the function you're removing this time).

You should define disableClicksDuringScroll function just once, outside the scroll handler, since it doesn't refer to any local variables here. Then when you call removeEventListener it will find this handler.

You can also use a variable so you only add the click listener once, when scrolling starts, not every time you reset the timer.

 this.disableClickDuringScrollHandler = (e) => { e.preventDefault(); }; this.inScroll = false; this.scrollHandler = e => { console.log('scrolling'); if (!this.inScroll) { document.addEventListener('click', this.disableClickDuringScrollHandler); this.inScroll = true; } window.clearTimeout(this.scrollTimer); this.scrollTimer = window.setTimeout(() => { this.inScroll = false; console.log('scroll end'); document.removeEventListener('click', disableClickDuringScrollHandler); }, 300); } window.addEventListener('scroll', this.scrollHandler); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM