Understanding the Event Module & Event Emitter Class in Node Js.

Understanding the Event Module & Event Emitter Class in Node Js.

Part 1

ยท

2 min read

The event module brings real-time event-driven programming in Node JS and it's one of many core modules to understand.

events.jpeg

So what is an Event?

In simple terms, an event is a signal / request or click that something has been triggered in our application. For example, let's say we have a web server with an assigned port that receives and sends back data, anytime there is a request on the port, the HTTP request raises an Event.

The EventEmitter Class

The EventEmitter class is used to handle events in Node JS and it has collections of methods. The most used methods used are

.on  
.addListener 
.emit

In writing a simple event, you have to take into consideration to first register a listener and later trigger an event.

//import the module
const EventEmitter = require('events');

//initiate an instance of the class, this is usually an object 
const emitter = new.EventEmitter();

//Register a listener. This also takes a callback function and pass a parameter
emitter.on('EventLogged', function(logmsg)=>{
     console.log(logmsg)
});

//Raise an event and pass the arg from the function
emitter.emit('EventLogged',  'Event was fired');
$ node app
Event is fired

Now as we have a general understanding of how to write a simple event listener, we will write a custom event listener on objects which logs an event. For this example, we will use the util module which is used to inherit objects built-in Node Js

//import modules
const event = require('events');
const util = require('util');

// create a new object constructor function
const Person = function (name) {   
    this.name = name 
}

// Person is now an EventEmitter
util.inherits(Person, event.EventEmitter)  

//create people variables
const wade = new Person('wade')
const nii = new Person('nii')
const kofi = new Person('kofi')
const kwame = new Person('kwame');
const pat = new Person('pat');

//store people in an array
const people = [wade, nii, kofi, kwame, pat]

//write loop to cycle through people array
people.forEach(person => {
    //Event listener 
    person.on('type', (msg) => {
        console.log(`${person.name} typed: ${msg}`);
    });
});

//Event emitter
wade.emit('type', 'hello');
nii.emit('type', 'sap fam')
kofi.emit('type', 'yo,we good')
kwame.emit('type', 'any plans')
pat.emit('type', 'Dinner bills on me fam')
$ node app
wade typed: hello
nii typed: sap fam
kofi typed: yo,we good
kwame typed: any plans
pat typed: Dinner bills on me fam

Viola !!! I hope you have understood how to use this module and you will translate this knowledge into practice to help you become a great developer. if you found this helpful, please give it a ๐Ÿ‘ and leave a comment. You can also follow me on Twitter @niiwadey

Happy Coding Guys !!!

ย