Skip to content

Instantly share code, notes, and snippets.

@chrisdc
Last active August 29, 2015 14:08
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 chrisdc/30968d081565724c7b5f to your computer and use it in GitHub Desktop.
Save chrisdc/30968d081565724c7b5f to your computer and use it in GitHub Desktop.
Publish/subscribe module
/**
* A simple Publish/subscribe javascript module based on code by David Walsh:
* http://davidwalsh.name/pubsub-javascript
*/
var events = (function(){
// Holds the subscribed topics.
var topics = {};
return {
subscribe: function( topic, callback ) {
// Create the topic's object if not yet created.
if( ! topics[topic] ) {
topics[topic] = { subscribers: [] };
}
// Add the callback to subscribers list.
var index = topics[topic].subscribers.push( callback ) - 1;
// Remove subscriber from a topic.
return {
remove: function() {
delete topics[topic].subscribers[index];
}
};
},
publish: function(topic, info) {
// Return early if the topic doesn't exist, or there are no subscribers.
if( ! topics[topic] || ! topics[topic].subscribers.length ) {
return;
}
// Cycle through topics subscribers, fire!
var items = topics[topic].subscribers;
for ( var i = 0, len = items.length; i < len; i++ ) {
items[i]( info || {} );
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment