问题描述
如何删除绑定到构造器
中的窗口
的点击侦听器下面?我需要它来监听窗口
,并且需要访问其中的按钮实例。
How do I remove the click listener I bound to window
in the constructor
below? I need it to listen on window
, and I need access to the button instance inside it.
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
创建一个新的单独函数,并且如果传递的函数相同,则只能调用 removeEventListener
删除侦听器( ===
)作为传递给 addEventListener
的那个(就像 .includes
一样) ,或对于集合来说 .has
):
It's not possible with your current implementation - every call of .bind
creates a new separate function, and you can only call removeEventListener
to remove a listener if the passed function is the same (===
) as the one passed to addEventListener
(just like .includes
for arrays, or .has
for Sets):
const fn = () => 'foo';
console.log(fn.bind(window) === fn.bind(window));
作为解决方法,您可以将绑定函数分配给实例的属性:
As a workaround, you could assign the bound function to a property of the instance:
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>
这篇关于删除已使用bind(this)添加的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!