如何删除使用“this”的事件监听器?在TypeScript? [英] How do you remove an event listener that uses "this" in TypeScript?
问题描述
在JavaScript中,对于需要访问私有成员和函数的事件处理程序,我可以依赖于在我的事件处理函数中可访问的函数范围,并执行以下操作:
In JavaScript, for an event handler that needs access to private members and functions, I can rely on the function scope of those to be accessible within my event handler function, and do something like this:
theElement.addEventListener("click", onClick);
及以后:
theElement.removeEventListener("click", onClick);
在TypeScript中,我需要使用匿名函数 this
是包含对象,如下所示:
In TypeScript, I need to use an anonymous function to have this
be the containing object, like so:
theElement.addEventListener("click", (event) => this.onClick(event));
在这种情况下,我无法从侦听事件中删除匿名函数。我如何将一个事件监听器作为一个类的一部分(可以访问私有字段和方法),我可以在以后删除它?
In this case, I can't remove the anonymous function from the listening to the event. How do I have an event listener as part of a class (with access to private fields and methods), that I can remove later?
推荐答案
首先,即使你这样写,JavaScript和TypeScript的行为也完全相同:
First, JavaScript and TypeScript behave the exact same way even if you write like that:
theElement.addEventListener("click", onClick);
其次,这是保留对匿名函数的引用的方法:
Second, this is how you can retain a reference to an anonymous function:
var f = (event) => this.onClick(event);
theElement.addEventListener("click", f);
// later
theElement.removeEventListener("click", f);
如果你正在处理事件监听器,那么绑定类方法有一个有用的模式:
If you're dealing with event listeners, there's a useful pattern for your class methods to be bound:
class MyClass {
init(theElement) {
theElement.addEventListener("click", this.onClick);
theElement.addEventListener("click", this.onClick2);
}
print() {
console.log("print");
}
onClick() {
this.print() // possible error (`this` is not guaranteed to be MyClass)
}
onClick2 = () => {
this.print() // no error, `this` is guaranteed to be of type MyClass
}
}
但请记住,此代码将为类<$ c的每个对象创建一个单独的函数 onClick2
$ C> MyClass的。如果您创建大量 MyClass
实例并且很少使用他们的 onClick
侦听器,那可能会对您的内存使用产生负面影响。
Keep in mind, however, that this code will create a separate function onClick2
for every object of class MyClass
. That can negatively affect your memory usage, if you create lots of MyClass
instances and rarely use their onClick
listeners.
这篇关于如何删除使用“this”的事件监听器?在TypeScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!