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:
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