Parvati River, Himanchal

Understanding PubSub design pattern in JavaScript

--

In JavaScript lot of actions are event-driven. In our daily practice we use such event and actions a lot. onClick onChange are the examples of some events and we perform some actions whenever these event occurs.

Using Pub/Sub we can leverage 😃 this event driven approach and introduce it it our logical side of application. To isolate business logic from our application layer.

Before getting into the code lets understand Pub/Sub by an analogy of Newsletter subscription. Suppose 🤔 we have a newsletter subscription. Whenever new article is published, the newly baked ♨️ article is delivered to our mailbox 📧. Our mailbox is responding to the event and handling the arrived notification.
Similarly in PubSub pattern we subscribe to an event by some uniqueId (userDefined). And whenever an event is published with eventId, all the handler which have subscription to this event get fired. 🚀.

Initial skeleton of Pub/Sub ☠️ looks like

Skeleton of Pub/Sub

cache object is used as container of all published and subscribed methods. Its shape can be defined as {eventId:[Array of callbacks]} .

First Lets fill sub method. In sub first I want to check if I am making subscription for event first time. If I am making subscription first time then I’ll directly assign my callback to cache object corresponding to passed eventId else I’ll push the callback in my cache object corresponding to passed eventId . As I may have more than one subscription for specific events. After this our code will look like this:

Subscription method of PubSub

Before moving to pub method we have to understand few concepts of javascript:
👆🏻 arguments array: every function in JavaScript has a special array-like variable arguments which holds all the arguments passed in a function.

✌️ call and apply methods can be used to invoke (call) a method with an owner object as an argument (parameter). These are inbuilt in JavaScript.

Now lets move to our pub method:

Publish method of PubSub

Lets fill the last piece, i.e. unsub method:

UnSubscribe method of PubSub

How to consume this: (Node Version)

  • Create a file called product.js . Publisher . Add Following code:
Publsiher
  • Create file called cart.js. Add the following code
Consumer (Subscriber)
  • Create a file called app.js . Main entry point or parent file. Add following code:
Entry Point

Extending the functionality: If you call product.onAdd() before importing cart . Then you subscription on cart won’t be called when you import it. Example:

Wasted Subscription

We can overcome this issue by extending pub/sub capability. For this we just have to change the shape of our cache object and make an additional iteration in sub method.

Here is the sample code for pub/sub design pattern. In mentioned git repo you can find both the versions.

https://github.com/rahuulmiishra/pubsub

--

--