Skip to content

Instantly share code, notes, and snippets.

@srijanshetty
Created June 24, 2014 05:18
Show Gist options
  • Save srijanshetty/b675ab657c1052cd6ba0 to your computer and use it in GitHub Desktop.
Save srijanshetty/b675ab657c1052cd6ba0 to your computer and use it in GitHub Desktop.
Pub Sub system
// Taken from David Walsh's blog
var events = (function() {
var topics = {};
return {
subscribe: function(topic, listener) {
if (!topics[topic]) {
topics[topic] = {
queue: []
};
}
var index = topics[topic].queue.push(listener);
return (function (index) {
return {
remove: function() {
delete topics[topic].queue[index]
}
};
})(index);
},
publish: function(topic, info) {
if( !topics[topic] || !topics[topic].queue.length) {
return ;
}
topics[topic].queue.forEach(function(element) {
element(info || {});
});
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment