A Simplest Publish-Subscribe Pattern in JavaScript

M.François
3 min readOct 25, 2019

--

There are many design patterns in JavaScript world and each of them has invented to solve specific problems which we face from the years ago to now. The Publish-Subscribe pattern is one of them.

When we want to receive data while an event completed in different files, then Pub-Sub pattern is a good choice.

There are multiple subscribers for one publisher, which means multiple files or objects can subscribe an event name and when a publisher publishes the data, then all the subscribers will receive the data immediately.

Let’s get started and see what the code looks like:

Create a class with name of YLNotificationMessages, and there is a constructor, and we create an event variable self.event which will include all events and callbacks.

class YLNotificationMessages {    constructor () { 
this.events = {};
}}

And we create the function of subscribe, which will subscribe all the callback with its event name, if the event name exists, then push the callback to that event list.

subscribe (eventName, callback) {     if (!this.events[eventName]) { 
this.events[eventName] = [callback];
} else {
this.events[eventName].push(callback);
}
}

And then we create a function of publish with arguments: (event name, arguments), and use the event name to find out the callback function and pass arguments to it and finally call the function immediately.

forEach is a for loop and call the function with arguments while looping. cb(…args) is very important, because it is calling the function.

publish (eventName, …args) { 
this.events[eventName] && this.events[eventName].forEach(cb => cb(…args));
}

Then, we’re going to find the callback in accordance with its event name and remove it from the event list. We use filter method which will filter all the unmatched methods, then it keeps the matched methods.

unsubscribe (eventName, callback) { 
if (this.events[eventName]) {
this.events[eventName].filter(cb => cb != callback);
}
}

Finally, register the class YLNotificationMessages to Windows Objects as a call in JavaScript

window[“YLNotificationMessages”] = new YLNotificationMessages();

The full code look like below, you can click here to open it on Github gist page.

We defined our Pub-Sub Pattern class and how do we use it in our code?

Whenever you want to subscribe in certain files or functions or modules, it looks like this code snippet:

window.YLNotificationMessages.subscribe("ReceiveMessages", function(data) {
console.log(data);
});

The subscribe function can be called in many places in project with one event name of “ReceiveMessages”, and you can define multiple event name as you wish.

How to publish events in order to the subscribers receiving? The code snippet looks like below, you just call the function of “publish” in Window, and all the subscribers will receive the variable of “data” values.

var data = {
"user_id": 28648,
"user_name": "jd",
"user_language": "en",
"user_uuid": "8b3d1204-e2ee-11e9-9d7c-1f8e47066aae",
"user_email": "123456@gmail.com",
"user_avatar": "https://google.com/icon.png"
};
window.YLNotificationMessages.publish("ReceiveMessages", data);

If you think this article helps, please vote me up.

Thank you and have fun with code~

--

--