How do you remove an event listener that uses “this” in TypeScript?

后端 未结 3 1271
星月不相逢
星月不相逢 2021-02-12 11:28

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 functi

3条回答
  •  我在风中等你
    2021-02-12 12:09

    Already answered question, but IMO the answers here are not well designed regarding to OOP. So, here is my solution:

    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); 
      }
    
    }
    

提交回复
热议问题