I need to remove an event listener set on window, but it doesn't work, the listener keeps firing on scroll. I've tried to set the listener with and without lodash's throttle but it doesn't make any difference. Here's my code:
setupListener() {
window.addEventListener('resize', _.throttle(this.handler.bind(this), 750));
window.addEventListener('scroll', _.throttle(this.handler.bind(this), 750));
}
removeListener() {
window.removeEventListener('resize', _.throttle(this.handler.bind(this), 750));
window.removeEventListener('scroll', _.throttle(this.handler.bind(this), 750));
window.addEventListener('load', this.handler.bind(this), false);
}
static isElementInViewport (el) {
let rect = el.getBoundingClientRect();
return (
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
handler() {
if (this.options.url === undefined) {throw new Error('no url specified');}
if (InfiniteScroll.isElementInViewport(this.elementToWatch)) {
this.removeListener();
this[this.options.transport]();
}
}
I've also tried to promisify the removal:
handler() {
if (this.options.url === undefined) {throw new Error('no url specified');}
if (InfiniteScroll.isElementInViewport(this.elementToWatch)) {
Promise.resolve(this.removeListener())
.then(val => {
this[this.options.transport]();
});
}
}
which didn't make a difference either.
Later in the code, I want to reassign the listeners:
handleResponse(data) {
console.log('handleResponse' + data);
Promise.resolve(this.addElementsToDOM(data))
.delay(1000)
.then(() => {
this.page++;
this.elementToWatch = document.getElementById(this.element).rows[document.getElementById(this.element).rows.length - this.options.loadTiming];
//this.setupListener();
});
}
I've logged every step of the and am unable to find the reason for it. Can someone please assist?
Sidenote: Is there a better way of handling the scroll event than to remove and add the listeners all the time?