Node.js EventEmitter: How to bind a class context to the event listener and then remove this listener
You could do this in the constructor:
this.handleTestEvent = this.handleTestEvent.bind(this);
this.emitter.addListener("test", this.handleTestEvent);
If you want to use cutting edge, you can use the proposed bind operator as a shortcut:
this.handleTestEvent = ::this.handleTestEvent;
this.emitter.addListener("test", this.handleTestEvent);
Or use a property initializer to create a bound method:
constructor(private text: string) {
this.emitter = new EventEmitter();
this.emitter.addListener("test", this.handleTestEvent);
this.emitter.emit("test");
}
handleTestEvent = () => {
console.log(this.text);
}