TypeScript, how to keep class methods event handlers context to “this” instance

前端 未结 2 779
悲&欢浪女
悲&欢浪女 2021-01-01 14:17

I have an issue with Classes in TypeScript. each time I have to listen to an HTML Element events I need to use Function.bind() to connect it to the current instance.

2条回答
  •  抹茶落季
    2021-01-01 14:47

    You can also cache the controller context. I use this style a lot, when working with d3.js. This way I still have access to the context of the callback, which in d3 refers usually to an element.

    private onClick(): Function {
      controller: this = this;
      return function(event) {
        controller.anotherClassFunction();
      };
    }
    
    private secondFunction(): void {
      this.addEventlistener(this.onClick());
    }
    

提交回复
热议问题