javascript – 删除使用bind(this)添加的事件侦听器
作者:互联网
如何在下面的构造函数中删除绑定到窗口的单击侦听器?我需要它来监听窗口,我需要访问其中的按钮实例.
class MyEl extends HTMLButtonElement {
constructor() {
super();
this.clickCount = 0;
window.addEventListener('click', this.clickHandler.bind(this));
}
clickHandler(e) {
if (e.target === this) {
this.textContent = `clicked ${++this.clickCount} times`;
window.removeEventListener('click', this.clickHandler);
}
}
disconnectedCallback() {
window.removeEventListener('click', this.clickHandler);
}
}
customElements.define('my-el', MyEl, { extends: 'button' });
<button is="my-el" type="button">Click me</button>
解决方法:
你当前的实现是不可能的 – 每次调用.bind都会创建一个新的独立函数,如果传递的函数与传递给addEventListener的函数相同(===),你只能调用removeEventListener来删除一个监听器(就像.includes用于数组,或.has用于集合):
const fn = () => 'foo';
console.log(fn.bind(window) === fn.bind(window));
作为解决方法,您可以将绑定函数分配给实例的属性:
class MyEl extends HTMLButtonElement {
constructor() {
super();
this.clickCount = 0;
this.boundListener = this.clickHandler.bind(this);
window.addEventListener('click', this.boundListener);
}
clickHandler(e) {
this.textContent = `clicked ${++this.clickCount} times`;
window.removeEventListener('click', this.boundListener);
}
}
customElements.define('my-el', MyEl, { extends: 'button' });
<button is="my-el" type="button">Click me</button>
标签:javascript,ecmascript-6,addeventlistener,custom-element,removeeventlistener 来源: https://codeday.me/bug/20190607/1193634.html