JavaScript PubSub
One of the most useful implementations of software design patterns is the “PubSub” pattern. “PubSub” is a shorthand term for “Publish-Subscribe” which is a description of what the pattern is actually doing. The reason it is so useful is because it is so universal to how applications work. Basically the idea is that you have pieces of code (publishers) that say “something happened” — a user logged in, there was an error retrieving data, a button was clicked — it could be anything. Then you have pieces of code (subscribers) that run when those events occur. They are called subscribers because they subscribe to the event that gets published. PubSub implementations will also have some sort of capability for previously set subscribers to unsubscribe from an event. If that event happens again after this, the subscriber code will no longer execute.
Sometimes the terms used in PubSub pattern can vary. Sometimes “subscribers” are referred to as “listeners” because they “listen” for certain events occurring. You might recognize this in things like JavaScript’s addEventListener where you can attach callback functions to run when certain DOM events (such as button clicks and mouse hovers) occur. jQuery’s on, off, and trigger methods, are 3 methods that you can use in tandem to easily implemennt PubSub, with “on” being the subscribe functionality, “off” being unsubscribe, and “trigger” being the publish functionality. Backbone.js also uses on, off and trigger in its eventing system. Whatever the terms are and however the code is structured, ultimately these are just variations of the PubSub pattern and will nearly always follow similar ideas and principles.
A lot of examples of PubSub will use something that is pre-built, like jQuery’s methods mentioned above, or a library that implements it, but what we’re going to do in the following paragraphs is look at a raw JavaScript implementation of PubSub where we can do brodcasting (publishing) of our own custom events and attach subscribers to these events. This will give us a good understanding of how PubSub works under the hood. Our implementation will be pretty simple and it will only handle custom events that we name ourselves, but it could be taken and expanded upon to include more standard universal events such as mouse events, load events, error events, and others.




