Node.js – Event Emitters

Callbacks are emitted and bound to an event by using a consistent interface, which is provided by a class known as EventEmitter . In real life, EventEmitter can be likened to anything that triggers an event for anyone to listen to. EventEmitter implementation involves the following steps:

  1. Importing and loading the event modules by invoking the “require” directive.
  2. Creating the emitter class that extends the loaded event module.
  3. Creating an instance of the emitter class.
  4. Adding a listener to the instance.
  5. Triggering the event.

EventEmitter Implementation

You can implement the EventEmitter by creating an EventEmitter instance using the following code:

var eEmitter = require('events'); // events module from node class emitter extends eEmitter {} // EventEmitter class extended
var myeEmitter = new emitter(); // EventEmitter instance

The AddListener Method

EventEmitter makes it possible for you to add listeners to any random event. For flexibility, multiple callbacks can be added to a single event. Either addListener(event, listener) or on(event, listener) can be used to add a listener because they perform similar functions. You can use the following code block to add listeners:

var emitter = new MyClass();
emitter.on('event', function(arg1) { … });

You can also use the following code block to add listeners:

emitter.EventEmitter.addListener(event, function(arg1) {


Trigger Events

To trigger an event, you can use emit(event, arg1), as can be seen here:

EventEmitter.emit(event, arg1, arg2……)

The .emit function takes an unlimited number of arguments and passes them on to the callback(s) associated with the event. By putting all of this code together, we have the following snippet:

var eEmitter = require('events');
class emitter extends eEmitter { } var myEemitter = new emitter(); myEemitter.on('event', () => {     
console.log('Hey, an event just occurred!');

Removing Listeners

We can also remove a listener from an event by using the removeListener(event,

listener) or removeAllListeners(event) functions. This can be done using the following code:

EventEmitter. removeAllListeners (event, arg1, arg2……)

Alternatively, you can use the following code:

EventEmitter. removeListener(event, listener) 

EventEmitter works synchronously; therefore, listeners are called in the order in which they are registered to ensure proper sequencing of events. This also helps avoid race conditions or logic errors. The setImmediate() or process.nextTick() methods make it possible for a listener to switch to an asynchronous mode.

For example, let’s say we wanted an output such as ” Mr. Pick Piper “. We could use the following code:

console.log ("Mr.");

However, if we want an output such as ” Mr. Piper Pick ” using the

Paul Oluyege. MongoDB, Express, Angular, and Node.js Fundamentals (Kindle Locations 664-682).

Leave a Comment