cathy.sasaki
cathy.sasaki

Reputation: 4025

How to remove different listeners on the same object that are also listening to the same event?

Does an event and a listener on a certain object act as an "identifying pair" for that listener? Or just the event on the object?

reading over node.js documentation here: http://nodejs.org/api/events.html#events_emitter_removelistener_event_listener

For example, if you have two callback functions listener_1 and listener_2:

var stdin = process.stdin;

stdin.on('data',listener_1);
stdin.on('data',listener_2);

then you remove the listener, with:

stdin.removeListener('data',listener_1);

So, is listener_2 still listening?

Thank you.

ps. I tried test myself using util.inspect and listeners method but still not confident I understood how this works!

Upvotes: 3

Views: 4477

Answers (2)

Ben
Ben

Reputation: 35613

You can use an anonymous function but you need to save it somewhere.

var listener = function(){};
emitter.on('event', listener);
emitter.removeListener('event', listener);

But that means you can't use bind or the arrow function closure notation:

emitter.on('event', listener.bind(this));// bind creates a new function every time
emitter.removeListener('event', listener.bind(this));// so this doesn't work

emitter.on('event', ()=>{});// closure creates a new function every time

Which is annoying. This works though:

emitter.on('event', this.eventListener = () => {});
emitter.removeListener('event', this.eventListener);

So does this (storing listeners in a map):

emitter.on('event', this.listeners['event'] = this.myEventListener.bind(this));
emitter.removeListener('event', this.listeners['event']);

This is not always an issue:

  • In the most common case there is only one listener.
  • In the second most common case, there can be more than one but they all want removing together (e.g. because the emitter has finished its job).

Either way, you won't need to specify the function. However when you do, you do.

Upvotes: 4

Utopik
Utopik

Reputation: 3783

If you want to remove all the listeners, you can use

stdin.removeAllListeners('data')

Otherwise, after calling

stdin.removeListener('data',listener_1);

listener_2 is still listening.

Upvotes: 11

Related Questions