Node.js EventEmitter: How to bind a class context to the event listener and then remove this listener

眉间皱痕 提交于 2019-12-01 17:03:53
robertklep

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

I was also unable to remove the listener in a class. This worked for me (see: https://nodejs.org/api/events.html#events_emitter_rawlisteners_eventname)

emitter.on('error', this.onError.bind(this));
this.onErrorListener = emitter.rawListeners('error').splice(-1)[0];
...
emitter.off('error', this.onErrorListener);

You probably sorted this out but you could just have done

import {EventEmitter} from "events";

class HasEvents extends EventEmitter {}

const emitter = new HasEvents();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!