2

Consider the following node.js cluster config. How does one turn off the callback to prevent further on message callbacks? There happens to be no off method. I have to update the callback with a new one and it appears that all the old callbacks are being triggered as well.

     cluster.on('fork', worker => {
        worker.on('message', msg => {// Do something...})
      })
Anshuul Kai
  • 3,876
  • 2
  • 27
  • 48

2 Answers2

6

The opposite of .on() is .removeListener() because .on() is simply an alias for .addListener(). Why they added .on() as an alias, but did not add .off() as an alias too, I don't really know (seems logical to me).

But, to be able to remove a single listener with removeListener(), you need a function reference for the function you originally attached. So, you need to save that:

 cluster.on('fork', worker => {
     function msgHandler(msg) {
         // process message
     }

     // add event handler
     worker.on('message', msgHandler);

     // then, sometime later, to remove the event handler
     worker.removeListener('message', msgHandler);
 });

If you just want to remove all event listeners for a given event, you don't have to save the former function reference:

 cluster.on('fork', worker => {
     worker.on('message', msg => {// Do something...})

     // some time later, remove all listeners for a particular message
     worker.removeAllListeners('message');
 });

Related answer: What is the difference between addListener(event, listener) and on(event, listener) method in node.js?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    @anshulkoka - Does this answer your question? If so, you can indicate that to the community by clicking the green checkmark to the left of the answer and that will also earn you some reputation points. – jfriend00 Aug 18 '17 at 06:15
0

You can use removeListener method. https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener

Anatoly Strashkevich
  • 1,834
  • 4
  • 16
  • 32