How to use EventEmitter from Node.js In Javascript

Node.js provides a built-in EventEmitter class that can be used to implement the Pub/Sub pattern effectively within a JavaScript application, especially when using Node.js or in environments where this class is available.

Example:

JavaScript
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

// Subscribe to an event
myEmitter.on('myEvent', (data) => {
  console.log('Event received:', data);
});

// Emit an event
myEmitter.emit('myEvent', 'Hello, EventEmitter!');

// Additional subscriber
myEmitter.on('myEvent', () => {
  console.log('Another subscriber received the event');
});

// Emit the event again
myEmitter.emit('myEvent', 'Second emit');

// Unsubscribe from an event
const handler = (data) => {
  console.log('Handler function:', data);
};
myEmitter.on('otherEvent', handler);
myEmitter.off('otherEvent', handler); // Node.js v15.0.0 or later





JavaScript Program for Making a Case for Signals

In this article, we will learn about Making a case for Signals in JavaScript, In the dynamic landscape of modern web development, efficient communication among different components of an application is crucial and JavaScript being an asynchronous language demands a robust mechanism to handle such inter-component communication seamlessly and this is where signals come into play and Signals offer an elegant and effective solution for the managing interactions between different parts of your JavaScript application

We can create cases for signals by these approaches:

Table of Content

  • Using Custom Events
  • Using the Pub/Sub Pattern

Similar Reads

Using Custom Events

...

Using the Pub/Sub Pattern

Custom events are a powerful feature in JavaScript that allows you to create and dispatch your own custom events. In this approach, we are creating a custom event called ‘gfgEvent’. And creating a new div element.We are adding an event listener to that newly created element and printing the event type in the console.At the end, we are dispatching the event....

Using EventEmitter from Node.js

The Publish/Subscribe (Pub/Sub) pattern is a popular approach for the implementing signals. like EventEmitter or PubSubJS simplify its implementation.The Pub/Sub pattern is based on the concept of channels and publishers emit messages on specific channels and subscribers listen to those channels for the relevant messages. This pattern is particularly useful when you have components that need to communicate asynchronously...