无法删除eventListener

时间:2016-07-20 11:16:23

标签: javascript

我有一个侦听滚动的函数,但我需要多次调用它。这会导致事件监听器堆叠。所以我尝试在添加之前删除一个,如下所示:

  watchButton() {
    console.log('watching button');
    const button = document.getElementById('load-more-news');
    const fetcher = () => {
      let windowHeight = document.body.offsetHeight / 2;
      let offset = button.getBoundingClientRect().top;
      if (offset <= windowHeight) {
        button.click();
      }
    };

    window.removeEventListener('scroll', throttle(fetcher, CONFIG.THROTTLE), true);
    window.addEventListener('scroll', throttle(fetcher, CONFIG.THROTTLE), true);
  }

我还尝试将throttle函数绑定到其他变量:

const fetcher = () => {
  let windowHeight = document.body.offsetHeight / 2;
  let offset = button.getBoundingClientRect().top;
  if (offset <= windowHeight) {
    button.click();
  }
};

const boundFetcher = throttle(fetcher, CONFIG.THROTTLE);

window.removeEventListener('scroll', boundFetcher, true);
window.addEventListener('scroll', boundFetcher, true);

但是当我在Chrome中检查事件监听器选项卡时,我在这里初始化了两个(和更多)滚动侦听器。我该怎么办?

1 个答案:

答案 0 :(得分:0)

每次调用watchButton时,您都在重新创建功能参考,因此fetcherthrottle(fetcher,...)每次调用watchButton时都会有所不同。

const不会在多次调用watchButton

时使变量保持不变

const变量移到watchButton函数

之外
const button = document.getElementById('load-more-news');
const fetcher = () => {
  let windowHeight = document.body.offsetHeight / 2;
  let offset = button.getBoundingClientRect().top;
  if (offset <= windowHeight) {
    button.click();
  }
};
const throttledFetch = throttle(fetcher, CONFIG.THROTTLE);

watchButton() {
  window.removeEventListener('scroll', throttledFetch, true);
  window.addEventListener('scroll', throttledFetch, true);
}