Skip to content

Instantly share code, notes, and snippets.

@hwclass
Created June 12, 2014 19:00
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 hwclass/11c85272efdda84c36ff to your computer and use it in GitHub Desktop.
Save hwclass/11c85272efdda84c36ff to your computer and use it in GitHub Desktop.
A Pub / Sub Sample
var events = (function(){
var topics = {};
return {
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);
// Provide handle back for removal of topic
return (function(index) {
return {
remove: function() {
delete topics[index];
}
}
})(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;
for(var x = 0; x < items.length; x++) {
items[x](info || {});
}
}
};
})();
/*initialize an event subscription*/
var testSub = events.subscribe('/page/load', function(obj) {
console.log('test sub callback after /page/load occurs.');
});
/*publish an event*/
events.publish('/page/load', {
url: '/some/url/path' // any argument
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment