gpt4 book ai didi

javascript - 如何从类方法中删除事件监听器

转载 作者:行者123 更新时间:2023-11-30 14:00:14 25 4
gpt4 key购买 nike

我正在尝试使用与添加事件监听器相同的引用从函数中删除事件监听器,但 removeEventListener 不起作用

我想要 onScroll 方法停止监听滚动。

export class LazyLoad {
constructor(elementoScroll, porcentagem, objetoAxios) {
this.elementoScroll = elementoScroll
console.log(this.elementoScroll.scrollTop)
this.porcentagem = porcentagem
this.objetoAxios = objetoAxios
this.endereco = objetoAxios
this.addListener()
}

addListener() {
this.elementoScroll.addEventListener('scroll', this.onScroll.bind(this), true);
}

onScroll(event) {
console.log(event)
let scrollPorcentagem = Math.floor(this.elementoScroll.scrollTop / (this.elementoScroll.scrollHeight - this.elementoScroll.clientHeight) * 100);
if(scrollPorcentagem >= 90) {
this.elementoScroll.removeEventListener('scroll', this.onScroll, true);
}

}
}

最佳答案

addEventListenerreoveEventListener 调用的函数参数不同。要了解这一点,请看这个简化的示例:

class X { method() {} }
let x = new X();
console.log(x.method.bind(x) === x.method); // false

要解决这个问题,请保留对添加事件监听器时使用的函数的引用:

class LazyLoad {
constructor(elementoScroll, porcentagem, objetoAxios) {
this.elementoScroll = elementoScroll;
console.log(this.elementoScroll.scrollTop);
this.porcentagem = porcentagem;
this.objetoAxios = objetoAxios;
this.endereco = objetoAxios;
this.addListener();
}

addListener() {
this.listener = this.onScroll.bind(this);
this.elementoScroll.addEventListener('scroll', listener, true);
}

onScroll(event) {
console.log(event);
let scrollPorcentagem = Math.floor(this.elementoScroll.scrollTop / (this.elementoScroll.scrollHeight - this.elementoScroll.clientHeight) * 100);
if (scrollPorcentagem >= 90) {
this.elementoScroll.removeEventListener('scroll', this.listener, true);
}

}
}

关于javascript - 如何从类方法中删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56431525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com