PubSub in Javascript

If you’re working on a large app, it’s important that all your system remains flexible. Nothing is worse than coding yourself into a corner. One of my favorite Javascript design patterns is PubSub. Go ahead and say that out loud a few times. It’s got a nice flow to it doesn’t it?


PubSub, which is short of Publish Subscribe (which is not nearly as fun to say), is a way of “decoupling” your code. Basically one method publishes, messages such as objects, and another method subscribes to it. It’s beauty is in it’s simplicity.

“In software engineering, coupling or dependency is the degree to which each program module relies on each one of the other modules.”- Wikipedia

Try to avoid coupling in your Javascript applications. PubSub lets you send whatever message you wish to whatever listening, without having to sorry about scope. (The communication flow reminds me of an old fashioned radio broadcast).

pub("dance", "hustle");

var danceVar = sub('symbolMethod', function(obj) {
	if (obj === "hustle") alert ("Do the hustle!");

Whenever you broadcast on the “dance” channel, whatever is subscribed to that will receive it.

broadcast = (function() {  
    var topics = {};
    return {
        sub: function(topic, listener) {
            if (!topics[topic]) topics[topic] = {
                queue: []
            var index = topics[topic].queue.push(listener) - 1;
            return {
                remove: function() {
                    delete topics[topic].queue[index];
        pub: function(topic, info) {
            if (!topics[topic] || !topics[topic].queue.length) return;

            var items = topics[topic].queue;
            items.forEach(function(item) {
                item(info || {});

Is this like DOM events?

Similar in concept, but different. PubSub is similar in that it’s an action triggered by an event, but has nothing to do with the DOM or event methods. This makes it an extremely useful pattern if you’re working without a DOM like with Node.

More Recourses

There are a TON of PubSub libraries out there. I think it’s faster to write my own than to learn someone else’s library. But if you want more features, you have many to choose from.

For more Pub Sub, David Walsh has a great article here

If you have a half hour, …

Read More»