Skip to content

Instantly share code, notes, and snippets.

@mockdeep
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mockdeep/857f00477978e811f214 to your computer and use it in GitHub Desktop.
Save mockdeep/857f00477978e811f214 to your computer and use it in GitHub Desktop.
javascript pub/sub
var events = (function(){
var topics = {};
function getQueue(topic) {
topics[topic] = topics[topic] || [];
return topics[topic];
}
return {
subscribe: function(topic, listener) {
var index = getQueue(topic).push(listener) - 1;
},
remove: function(topic, listener) {
queue = getQueue(topic);
index = queue.indexOf(listener);
delete queue[index];
},
publish: function(topic, info) {
if(!topics[topic] || !topics[topic].queue.length) return;
var items = topics[topic].queue;
getQueue(topic).forEach(function(listener) {
listener(info || {});
});
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment