我有一个侦听滚动的函数,但我需要多次调用它。这会导致事件监听器堆叠。所以我尝试在添加之前删除一个,如下所示:
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中检查事件监听器选项卡时,我在这里初始化了两个(和更多)滚动侦听器。我该怎么办?
答案 0 :(得分:0)
每次调用watchButton
时,您都在重新创建功能参考,因此fetcher
和throttle(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);
}