¿Cómo eliminar diferentes oyentes en el mismo objeto que también están escuchando el mismo evento?

Hace un evento y oyente on a certain object act as an "identifying pair" for that listener? Or just the evento 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 y listener_2:

var stdin = process.stdin;


then you remove the listener, with:


Asi es listener_2 still listening?

Gracias por su atención.

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

preguntado el 05 de mayo de 13 a las 18:05

2 Respuestas

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


Otherwise, after calling


listener_2 is still listening.

contestado el 05 de mayo de 13 a las 18:05

Thanks. I'm still thinking this through. So, to be clear, you always need to reference the listener by the exact name?? What if you have an anonymous listener, such as stdin.on('data',function(data) { //do something}); How do you remove that? - cathy.sasaki

You cant. If you plan to remove it, you have to name your function. But, it's not the name that is important, it's the reference. var todelete = listener_1; stdin.removeListener('data',todelete); works; because todelete is a reference to the Listener. - Utopik

Great. Thanks @Utopik. That makes sense. - cathy.sasaki

Usted puede 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.

Respondido 12 Jul 15, 10:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.