Last Updated: February 25, 2016
·
6.799K
· mturnwall

Javascript Publish/Subscribe Pattern

The Publish/Subscribe (PubSub) pattern is a variation of the Observer pattern. It allows you to decouple and remove dependencies between your objects which can make your objects easier to re-use.

If you have ever done custom events in javascript or jQuery then you are familiar with the pattern but probably didn't realize it. Every time you bind an event using jQuery's on/bind/live methods you are implementing the Observer pattern. The PubSub pattern is just a twist on the Observer pattern. The Observer requires that the object that is receiving the event notifications also has to do the subscription. So this create a dependency because the Observer has to handle both subscriptions and notifications. The PubSub pattern allows an object to simply subscribe to an event using a "topic". Another object can then "publish" the topic which fires the subscribed event.

The PubSub sits between the objects. So multiple objects can publish a single topic. This decoupling is a big advantage of the PubSub pattern because modules can interact with each other without knowing each other's specifics. This is also a disadvantage. When you publish a topic you have to assume that there's a subscription on the end listening. If there isn't you won't receive any notification that something broke. It'll fail silently because no error actually happened.

When creating your subscriptions, use a variable for your topic. That way when you have a typo, javascript will tell you that you do. If you just use a string then when you have a typo your publish event will fail silently because javascript doesn't care if there's no subscribe event for the topic you specified.

var topic = 'myTopic';
$.subscribe(myTopic, callback);
$.subscribe('anotherTopic', callback);

// this will through an error
$.publish(topc, 'hello world');
// this will fail but no error will happen
$.publish('anothrTopic', 'hello world');

Use the Observer pattern when watching events in the same object and use PubSub when you need to have other objects call your methods in your object.

The library I like to use is jquery-tiny-pubsub. It ties into jQuery's event system so you know it's robust for whatever you want to do. The only drawback is that since it's event driven the first argument your event function receives is the event itself. So you'll need to ignore the first argument in your subscribed callbacks. You could use that first argument to find out the name of the subscribed event that was called and do some logic branching. So a single function can be used for many subscribed events.

Download a simple demo to see this pattern applied.