Last active
August 29, 2015 14:08
-
-
Save chrisdc/30968d081565724c7b5f to your computer and use it in GitHub Desktop.
Publish/subscribe module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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