如何在附加了 .bind(this) 的回调中移除 EventListener
How to removeEventListener on a callback with .bind(this) attached
如果我这样做:
document.addEventListener("mousedown", this.foo);
然后在函数内部 this.foo
然后使用以下方法删除它:
document.removeEventListener("mousedown", this.foo);
然后就可以了。
但是如果我这样做:
document.addEventListener("mousedown", this.foo.bind(this));
则该功能未被移除
有什么我可以做的吗?我必须在 foo 中有正确的上下文。
this.foo.bind(this)
返回一个不同于函数 this.foo
的函数。因此,您需要做的是继续引用 bind
返回的函数
var handler = this.foo.bind(this);
document.addEventListener("mousedown", handler);
document.removeEventListener("mousedown", handler);
如果我这样做:
document.addEventListener("mousedown", this.foo);
然后在函数内部 this.foo
然后使用以下方法删除它:
document.removeEventListener("mousedown", this.foo);
然后就可以了。
但是如果我这样做:
document.addEventListener("mousedown", this.foo.bind(this));
则该功能未被移除
有什么我可以做的吗?我必须在 foo 中有正确的上下文。
this.foo.bind(this)
返回一个不同于函数 this.foo
的函数。因此,您需要做的是继续引用 bind
var handler = this.foo.bind(this);
document.addEventListener("mousedown", handler);
document.removeEventListener("mousedown", handler);