Digging Into Event Emitters In Node.JS

23 / Jan / 2014 by Sakshi Tyagi 0 comments

In extension to my previous blog on Event Emitters Event Emitters In Node.JS, here we will see some variations in implementing Event Emitters.

We can bind more than one listeners to an event. For example:

var events = require('events');
var eventEmitter = new events.EventEmitter();
var printFruit = function printFruit()
 console.log('I like Mango!!');
var allFruits = function allFruits()
 console.log('I like all fruits!!');
eventEmitter.on('Fruits', printFruit);
eventEmitter.on('Fruits', allFruits);

Here, we have created event ‘Fruits’ and registered two events with it. Now when we emit this event, both functions are called. Similarly we can registered more functions to the same event.
I like Mango!!
I like all fruits!!

One more way to do this is passing all the functions as arguments and they will be called in the order in which they are passed. For Example:

eventEmitter.emit('Fruits', printFruit, allFruits);

The output will be same as above.

Note: We can also remove all the listeners registered to a specific event. Syntax:- eventEmitter.removeAllListeners([event]);


Leave a comment -