Skip to content

Instantly share code, notes, and snippets.

@lokimeyburg
Created March 7, 2014 19:06
Show Gist options
  • Save lokimeyburg/9417732 to your computer and use it in GitHub Desktop.
Save lokimeyburg/9417732 to your computer and use it in GitHub Desktop.
Simple PubSub with Javascript
/*
## Simple PubSub with Javascript
### Usage:
var client = pubsub.subscribe('myChannel', function(data){
console.log(data);
});
pubsub.publish( 'myChannel', 'Hello World!' );
pubsub.publish( 'myChannel', { event: '/comment/new', msg: 'my comment' } );
pubsub.unsubscribe( client );
*/
var pubsub = {};
(function(p) {
var channels = {}, subscriberCount = -1;
p.subscribe = function(channel, func) {
if (!channels[channel]) {
channels[channel] = [];
}
var subscriberId = (++subscriberCount).toString();
channels[channel].push({
subscriberId: subscriberId,
func: func
});
return subscriberId;
};
p.publish = function(channel, args) {
if (!channels[channel]) {
return false;
}
setTimeout(function() {
var subscribers = channels[channel],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(args);
}
}, 0);
return true;
};
p.unsubscribe = function(subscriberId) {
for (var m in channels) {
if (channels[m]) {
for (var i = 0, j = channels[m].length; i < j; i++) {
if (channels[m][i].subscriberId === subscriberId) {
channels[m].splice(i, 1);
return subscriberId;
}
}
}
}
return false;
};
}(pubsub));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment