An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
September 10, 2020 06:49 am GMT
Original Link: https://dev.to/unalo_baayriyo/design-a-pub-sub-pattern-in-vanilla-js-4aa1
Design a pub sub pattern in vanilla JS
The Publisher/Subscriber pattern or PubSub is a design pattern that allows us to create powerful dynamic applications with modules that can communicate with each other without being directly dependent on each other.
To implement this we need-
- Publisher Method
- Subscriber Method
- Someplace to store callbacks and events that are registered from subscribers
So here we go -
// publisher// Subscriber// unsubscribe// Some place to store callbacks that are registered from subscribers.function pubSub() { // object which will track of all events and subscription const subscribers = {} // Publisher: function publish(eventName, data) { // return if event is not subscribed if (!Array.isArray(subscribers[eventName])) { return } // Whenever you publish any event, it will trigger callback for all stored event in subscriber object subscribers[eventName].forEach((callback) => { callback(data) }) } // Subscriber function subscribe(eventName, callback) { if (!Array.isArray(subscribers[eventName])) { subscribers[eventName] = [] } //on subscribe we will we will push callback to subscribers[eventName] array subscribers[eventName].push(callback); const index = subscribers[eventName].length - 1 // subscribed callbacks to be removed when they are no longer necessary. return { unsubscribe() { subscribers[eventName].splice(index, 1); }, } } return { publish, subscribe, }}
PubSub implementation is commonly seen in where there is -
- There is a portlet like implementation where there are multiple portlets that communicate with the help of an event bus.
- This helps in creating in aync architecture.In a system marred by tight coupling, pubsub is a mechanism which helps in communicating between various modules.
It is a very important concept from the perspective of the interview as it is frequently being asked in javascript interviews.
Original Link: https://dev.to/unalo_baayriyo/design-a-pub-sub-pattern-in-vanilla-js-4aa1
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To