Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple PubSub implementation with JavaScript - taken from Addy Osmani's design patterns book -
var pubsub = {};
(function(q) {
var topics = {}, subUid = -1;
q.subscribe = function(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
q.publish = function(topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
q.unsubscribe = function(token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
}(pubsub));
@sanketsahusoft

This comment has been minimized.

Copy link

sanketsahusoft commented Jul 9, 2013

This is awesome!

@daggmano

This comment has been minimized.

Copy link

daggmano commented Feb 14, 2015

Brilliant, many thanks.

@vothaison

This comment has been minimized.

Copy link

vothaison commented Feb 24, 2015

If your project has jQuery:

var
// use jquery as a pubsub manager
pubsub = $('<div>');

// say, in some place, you subscibe a event
pubsub.on('some-event', {somedata: "good day"}, function(e){
console.log('subscriber one ', e, this, arguments);
});

// and, in other place, you subscibe the same event
pubsub.on('some-event', {somedata: "hello world"}, function(e){
console.log('subscriber two ', e, this, arguments);
});

// Then you can publish the event/topic
pubsub.trigger('some-event', [ "Custom", "Arguments" ]);

// the object {somedata: "good day"}, {somedata: "hello world"}, are set to e.data

@ajaxray

This comment has been minimized.

Copy link

ajaxray commented Jul 18, 2016

@vothaison
PubSub is very similar to the DOM events, except: there is only one object which fires events and accepts listeners. So, though your solution will be a simple, just enough for some scenario, sometimes you'll need a real pubsub implementation.

@mocheng

This comment has been minimized.

Copy link

mocheng commented Jul 26, 2016

I don't understand why to have this loop
https://gist.github.com/fatihacet/1290216#file-pubsub-simple-js-L33-L34

It looks that the for (var m in topics) { is not necessary.

    q.unsubscribe = function(token) {
          if (topics[m]) {
              for (var i = 0, j = topics[m].length; i < j; i++) {
                  if (topics[m][i].token === token) {
                      topics[m].splice(i, 1);
                      return token;
                  } 
              }
         }
        return false;
     }
@tamal3053

This comment has been minimized.

Copy link

tamal3053 commented Oct 5, 2016

very nice

@rvenugopal

This comment has been minimized.

Copy link

rvenugopal commented Jan 11, 2017

I don't understand why notifying the subscribers is happening within a setTimeout. Is it because you want to return the publisher before the subscribers are notified / handled which can be potentially expensive?

@brajendraSwain

This comment has been minimized.

Copy link

brajendraSwain commented Apr 16, 2017

@rvenugopal - the code inside setTimeout will be executed asynchronously, so normal code flow(where it is publishing) won't halt.

@mshaaban088

This comment has been minimized.

Copy link

mshaaban088 commented May 11, 2017

@brajendraSwain While publishing, I'd prefer to have a loop, and for each subscriber, do the magic with setTimeout, to not block the other subscribers if one is doing heavy processing

var subscribers = topics[topic],
    len = subscribers ? subscribers.length : 0;
while (len--) {
    var notifier = (function(s, t, a) {
        return function() { s(t, a); };
    })(subscribers[len].func, topic, args);

    setTimeout(notifier, 0);
}
@frufin

This comment has been minimized.

Copy link

frufin commented May 19, 2017

Starting from this implementation, one can easily manage a silent reverse pub/sub to add bidirectionality :
https://github.com/frufin/js-bidirectional-pubsub

@Made-of-Clay

This comment has been minimized.

Copy link

Made-of-Clay commented Jul 12, 2017

@mocheng (nearly a year after your question...) The for...in loop allows an individual subscription to be cancelled (via the token returned upon subscribing). Removing the loop would destroy the event entirely, rather than a single subscription. A way around that might be to specify some ID token in the event like click.token. I'm not sure what arguments exist for which is better/worse.

Additionally, in your example, if (topics[m]) would fail because m is not defined without the loop. I'm guessing you meant something like topics[event] where event would be passed through the unsubscribe() params. For example:

// object definition
unsubscribe: function(event) {
    // ...
    if (topics[event]) {
    // ...
}
// code using pubsub
pubsub.unsubscribe('myAwesomeEvent');

With all of that said, you've probably already come to this conclusion after a year or don't care and have totally forgotten about this code. Either way, it was a good exercise for me ^_^

@galcyurio

This comment has been minimized.

Copy link

galcyurio commented Aug 8, 2017

some questions here!
If my thought was wrong, please tell me.
I am new to javascript!

https://gist.github.com/fatihacet/1290216#file-pubsub-simple-js-L17-L27

  1. I think it could be more simpler.
var subscribers = topics[topic];
if (!subscribers) {
    return false;
}

setTimeout(function(){
    for(var i=0, len = subscribers.length; i<len; i++) {
        subscribers[len].func(subscribers, args);
    }
}, 0);

https://gist.github.com/fatihacet/1290216#file-pubsub-simple-js-L34
2. and this conditional statement looks like unnecessary

https://gist.github.com/fatihacet/1290216#file-pubsub-simple-js-L22
3. also I can't understand why he used conditional statement here.
Is it unnecessary that we checked the conditional statement for undefined from the top?

ps. thank you for nice implementation. It was really helpful.

@scazzy

This comment has been minimized.

Copy link

scazzy commented Jul 31, 2018

While above is good, and it's crazily 7 years old. I try below method. Instead of using an array, I use an object for each subscriptions as well. Simpler and smaller Also note the unsubscribe closure return in publish, kinda helps.

PubSub.js

class PubSub {
  constructor () {
    this.subIds = 0;
    this.subscriptions = {}
  }
  
  subscribe (topic, fn) {
    if(!this.subscriptions[topic]) this.subscriptions[topic] = {}
    const token = ++this.subIds;
    // Validate topic name and function constructor
    this.subscriptions[topic][token] = fn;
    
    return () => this.unsubscribe(topic, token)
  }
  
  publish (topic, ...args) {
    const subs = this.subscriptions[topic];
    if(!subs) return false
    Object.values(subs).forEach(sub => sub(...args))
  }
  
  unsubscribe (topic, token) {
    if(!token) delete this.subscriptions[topic]; // Delete all subscriptions for the topic
    this.subscriptions[topic] && (delete this.subscriptions[topic][token]); // Delete specific subscription
  }
}

export default new PubSub();

Example

const unsub1 = PubSub.subscribe('spacex', data => console.log('Falcon was launched', data));
const unsub2 = PubSub.subscribe('spacex', data => console.log('Falcon Heavy was launched', data));
PubSub.publish('spacex', 'some data slash params')

// Unsubscribe single subscription
unsub1(); // Unsubscribes Falcon
unsub2(); // Unsubscribes Falcon Heavy

// Unsubscribe ALL subscriptions for a topic
PubSub.unsubscribe('spacex')

@ChiragMDave

This comment has been minimized.

Copy link

ChiragMDave commented Nov 3, 2018

This isn't publish subscribe pattern, this is the simplest observer pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.