Skip to content

Instantly share code, notes, and snippets.

@milesplit
Forked from fatihacet/pubsub-simple.js
Last active December 18, 2015 02:09
Show Gist options
  • Save milesplit/5708724 to your computer and use it in GitHub Desktop.
Save milesplit/5708724 to your computer and use it in GitHub Desktop.
var pubsub = (function(){
var q = {}, topics = {}, subUid = -1;
q.subscribe = function(topic, func) {
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;
};
return q;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment