Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 10, 2020 06:49 am GMT

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-

  1. Publisher Method
  2. Subscriber Method
  3. 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 -

  1. There is a portlet like implementation where there are multiple portlets that communicate with the help of an event bus.
  2. 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.

.kln


Original Link: https://dev.to/unalo_baayriyo/design-a-pub-sub-pattern-in-vanilla-js-4aa1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To