Open In App

JavaScript Program for Making a Case for Signals

Last Updated : 28 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using Custom Events

  • 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.

Example: This example shows the use of the above-explained approach.

Javascript




// Create a custom event
let gfgEvent = new Event('myEvent');
  
const newElement = document.createElement('div');
  
// Add an event listener to the dispatcher for the custom event
newElement.addEventListener('myEvent', function (event) {
    console.log('Custom event received:', event.type);
});
  
// Dispatch the custom event
newElement.dispatchEvent(gfgEvent);


Output:

Custom event received: myEvent
true

Using the Pub/Sub Pattern

  • 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

Example: This example shows the use of the above-explained approach.

Javascript




class PubSub {
    constructor() {
        this.subscribers = {};
    }
  
    subscribe(e, callback) {
        this.subscribers[e] = 
            this.subscribers[e] || [];
        this.subscribers[e].push(callback);
    }
  
    publish(e, data) {
        for (const subscriber of this.subscribers[e] || []) {
            subscriber(data);
        }
    }
}
const pubSub = new PubSub();
  
function handleEvent(data) {
    console.log('Received data:', data);
}
pubSub.subscribe('myEvent', handleEvent);
  
pubSub.publish('myEvent', 'Hello, gfg Pub/Sub!');


Output:

Received data: Hello, gfg Pub/Sub!


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads