Registering custom events in NodeJs using EventEmitter

Posted By : Nisheet Sharma | 29-Jan-2019

Introduction

We know the NodeJs core API has an asynchronous event-driven architecture. So, basically, there are objects that fire an event, which we call "emitters", and there are functions that get executed whenever a particular event is fired, which we call "listeners". All the "emitter" objects are instances of the "EventEmitter" class provided by the "events" core node module. We can make use of this class to create our own custom event emitters. Which then can be further used to create custom events with appended listener function(s) to perform various operations.

In this blog, we'll focus on how to create a simple custom event emitter and use it to fire a sample event, and perform a simple console log operation whenever our sample event is fired.

 

Prerequisites

1. NodeJs v6+ (https://nodejs.org/en/)

 

Usage

First, let's fetch the 'events' core module into our application as shown below:

const EventEmitter = require('events');

Now, we can use this 'EventEmitter' class, to create our own custom emitter class just by extending it. 

class CustomEmitter extends EventEmitter {}

Proceeding further, we can now use our CustomEmitter class to create an emitter instance as follows. 

const sampleEmitter = new CustomEmitter();

All the EventEmitter instances have an "on" method, which can used to register an event (if it doesn't already), and attach a listener function for the same. We can attach multiple listener functions for the same event if we want, but here we'll just register a single listener function for simplicity. 

sampleEmitter.on('sample-event', () => {
  console.log('sample-event listener executed!');
});

The above code will create an event with the name 'sample-event' and log the above mentioned message, whenever this event is fired.

Now, to fire our sample event, all we need to do is call the 'emit' method provided by the EventEmitter instance, as you can see below.  

sampleEmitter.emit('sample-event');

 

Conclusion

Thank you for reading this article. We learned how we can create our own custom events using the EventEmitter class. 

 

About Author

Author Image
Nisheet Sharma

Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.

Request for Proposal

Name is required

Comment is required

Sending message..