Search code examples
node.jscallbackeventemitter

How to set a callback function to be the first callback in EventEmitter?


I have a shared event emitter say myEmitter.

myEmitter.on('fire', callback1); 
myEmitter.on('fire', callback2); 
... 
myEmitter.on('fire', callbackN);

Now the problem is: I want myEmitter.on('fire', myTopCallBack); and I want myTopCallBack to be the first callback function to be called when 'fire' event happens.

Is it possible to subscribe a callback as the first callback?


Solution

  • You can use emitter.prependListener():

    myEmitter.on('fire', callback1); 
    myEmitter.on('fire', callback2); 
    ... 
    myEmitter.on('fire', callbackN);
    
    myEmitter.prependListener('fire', myTopCallBack);