Pub/Sub Pattern In JavaScript

Introduction

 
One of the most behavioural patterns used in JavaScript is the Publisher/Subscriber Pattern also known as “pubsub” pattern.
 
This pattern allows us to communicate different modules in application without hard dependencies between each other, but can still communicate indirectly. Therefore, this pattern is great for decoupling different parts of our code. This is a really useful pattern, but it is easy to overuse it. And that can get confused for anybody. However, in small systems or when it’s used wisely pubsub can be beneficial. 
 
So let’s type some lines of code and see how to implement it in JavaScript.
 
We are going to begin coding a module that with return the methods publish and subscribe, also we need an object to store callbacks and subscribers as the key.
 
object
 
We’ll begin with the method subscribe, which is going to register an event and a callback to execute when such an event gets invoked. We have to pass these two parameters and then inside the function, the first thing we have to do is to check whether the event already exists or not. If this event doesn’t exist, we can continue with the registration.
 
Code
 
Now, the publish method needs to receive two parameters as well, the first one will be the event to publish, and the second one will be the parameters that may be passed to the callback. The same logic that we just did with subscribe, we first checked if the event has been subscribed, in case it doesn’t just return.
 
check if the event has been subscribed
 
Since we can subscribe much callbacks for one event, we should use a “forEach” sentence to be able to execute all callbacks that has been bound to the event.
 
Then let’s create two different modules, which will depend on the pubsub module, but won’t depend on each other, they don’t even know about each other. In order to use the pubsub module inside these modules, we need to include it using require.
 
Let’s create our “exampleModuleA”.
 
ModuleA
 
And then our exampleModuleB that will expose and execute every event that has been subscribed to that specific event. Here is where we set the data to use in the callback
 
exampleModuleB
 
After having that we can write the main module to use the modules we have just created.
 
write a main module
 
Using the Chrome developer tools we can test this, and check if it works correctly.
 
Filter
 
We can see our modules are not tied between them, this way we have more flexibility in the structure of the code, you can notice how the exampleModuleA knows nothing about the exampleModuleA, However, they can make a link that complements each other to work well.
 
Well, I hope this will be helpful for you and can be used in your daily day activity. Happy coding.