You are here: Home / Topics / Event Emitter Pattern in Node Js

Event Emitter Pattern in Node Js

Filed under: NodeJs on 2024-02-22 20:51:05

AIM:
To demonstrate the event emitter pattern


Objective:
Explanation of event emitter pattern with programme.


Theory:
The EventEmitter is a module that facilitates communication/interaction between objects in Node. EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node‟s built-in modules inherit from EventEmitter including prominent frameworks like
Express.js. The concept is quite simple: emitter objects emit named events that cause previously registered listeners to be called. So, an emitter object basically has two main features:
 

  1. Emitting name events.
  2. Registering and unregistering listener functions.
     

It‟s kind of like a pub/sub or observer design pattern (though not exactly).
 

Explanation:
The $http.POST() service is used to deliver data to a certain URL and expects the resource at that URL to handle the request. In other words, the
POST method is used to insert new data based on a specified URL and is one of the $http service's shortcut methods.

Create an event emitter instance and register a couple of callbacks


const myEmitter = new EventEmitter();
function c1() {
console.log('an event occurred!');
}
function c2() {
console.log('yet another event occurred!');
}


myEmitter.on('eventOne', c1); // Register for eventOne
myEmitter.on('eventOne', c2); // Register for eventOne


When the event „eventOne‟ is emitted, both the above callbacks should be invoked.

myEmitter.emit('eventOne');
The output in the console will be as follows:
an event occurred!
yet another event occurred!

About Author:
T
Team MCQ Buddy     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.