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

object is used as container of all published and subscribed methods. Its shape can be defined as .

First Lets fill method. In 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 object corresponding to passed else I’ll push the in my object corresponding to passed . 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 method we have to understand few concepts of javascript:
👆🏻 array: every function in JavaScript has a special array-like variable which holds all the arguments passed in a function.

✌️ and 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 method:

Publish method of PubSub

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

UnSubscribe method of PubSub

How to consume this: (Node Version)

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

Extending the functionality: If you call before importing . Then you subscription on 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 object and make an additional iteration in 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

A passionate iOS Developer since 2014.