如何删除在TypeScript中使用"this"的事件侦听器?

Cur*_*ous 14 javascript dom-events typescript

在JavaScript中,对于需要访问私有成员和函数的事件处理程序,我可以依赖于在我的事件处理函数中可访问的函数范围,并执行以下操作:

theElement.addEventListener("click", onClick);
Run Code Online (Sandbox Code Playgroud)

然后:

theElement.removeEventListener("click", onClick);
Run Code Online (Sandbox Code Playgroud)

在TypeScript中,我需要使用匿名函数this作为包含对象,如下所示:

theElement.addEventListener("click", (event) => this.onClick(event));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我无法从侦听事件中删除匿名函数.我如何将一个事件监听器作为一个类的一部分(可以访问私有字段和方法),我可以在以后删除它?

zlu*_*mer 23

首先,即使你这样写,JavaScript和TypeScript的行为也完全相同:

theElement.addEventListener("click", onClick);
Run Code Online (Sandbox Code Playgroud)

其次,这是你如何保留对匿名函数的引用:

var f = (event) => this.onClick(event);
theElement.addEventListener("click", f);
// later
theElement.removeEventListener("click", f);
Run Code Online (Sandbox Code Playgroud)

如果您正在处理事件侦听器,那么绑定类方法有一个有用的模式:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

但请记住,此代码将为onClick2类的每个对象创建单独的函数MyClass.如果您创建了大量MyClass实例并且很少使用他们的onClick侦听器,那么这会对您的内存使用产生负面影响.

  • 最后一个代码块 `onClick2 = () => { }` 不是有效的 javascript。至少在 ES6 中? (2认同)

sci*_*per 8

已经回答了问题,但 IMO 此处的答案针对 OOP 设计得并不好。所以,这是我的解决方案:

export class MyClass {

  // create member that holds the function reference
  protected clickEventListener: EventListener;      

  // inject the Element
  constructor(protected theElement: Element) {   
    // wrap the class function `onClick` in an arrow function and assign 
    // to the class member `clickEventListener`   
    this.clickEventListener = () => this.onClick(); 
  }

  onClick() {
    console.log("clicked");
  }

  init() {
    // add the event listener to `theElement` and pass only the reference 
    // of `this.clickEventListener` (no round brackets '()')
    this.theElement.addEventListener("click", this.clickEventListener); 
  }

  destroy() {
    // to remve the event listener also just pass the `clickEventListener` reference
    this.theElement.removeEventListener("click", this.clickEventListener); 
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 我觉得大多数回复实际上都没有切中要害。这是一个非常清晰干净的解决方案,非常适合我的用例。没有任何细节混淆,感觉非常打字稿。多谢! (2认同)