Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Created January 30, 2015 17:48
Show Gist options
  • Save valerysntx/b5c71b9e604b8a7a36d1 to your computer and use it in GitHub Desktop.
Save valerysntx/b5c71b9e604b8a7a36d1 to your computer and use it in GitHub Desktop.
pubsub
var eventsystem = (function (eventsystem) {
var topics = {};
eventsystem = eventsystem || {
subscribe: function (topic, listener) {
// Create the topic's object if not yet created
if (!topics[topic]) topics[topic] = { queue: [] };
// Add the listener to queue
var index = topics[topic].queue.push(listener) - 1;
// Provide handle back for removal of topic
return {
remove: function () {
delete topics[topic].queue[index];
}
};
},
publish: function (topic, info) {
// If the topic doesn't exist, or there's no listeners in queue, just leave
if (!topics[topic] || !topics[topic].queue.length) return;
// Cycle through topics queue, fire!
var items = topics[topic].queue;
items.forEach(function (item) {
item(info || {});
});
}
};
return eventsystem;
})(eventsystem);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment