问题描述
调整窗口大小时,我试图有条件地在按钮上添加和删除事件侦听器。 为了能够删除事件侦听器,它必须是一个命名函数。
问题是它弄乱了this
上下文,因此我的handle()
函数中的this.element
无法访问。
我可以绑定this
并将其传递:
this.button.addEventListener('click', this.handle.bind(this));
但随后它不会被删除,因为它似乎不是同一事件侦听器。
我可以通过不同的方式传递this
,还是可以通过其他方法删除事件监听器?
我试图克隆元素并替换它,但是随后事件监听器没有重新连接。
按照这里:
这是一些简化的代码:
export default class Classname {
constructor(element, button) {
this.button = button;
this.element = document.querySelector(element);
this.resize();
}
handle() {
// do stuff
console.log(this.element);
}
clickEvents() {
if (condition) {
this.button.addEventListener('click', this.handle);
} else {
this.button.removeEventListener('click', this.handle);
}
}
resize() {
window.addEventListener('resize', () => {
this.clickEvents();
})
}
}
1楼
CertainPerformance
2
2019-03-02 21:18:44
您可以将绑定处理程序分配给实例的属性,然后将该绑定处理程序传递给addEventListener
以及以后的removeEventListener
:
clickEvents() {
if (condition) {
this.boundHandler = this.handle.bind(this);
this.button.addEventListener('click', this.boundHandle);
} else {
this.button.removeEventListener('click', this.boundHandle);
}
}
另一种可能性是绑定在构造函数中:
constructor(element, button) {
this.boundHandler = this.handle.bind(this);
this.button = button;
this.element = document.querySelector(element);
this.resize();
}
2楼
Gabriele Petrioli
1
2019-03-02 21:21:14
您可以将转换handle
的方法来箭头功能,那么this
将被保留。
handle = () => {
// do stuff
console.log(this.element);
}