Skip to content

Instantly share code, notes, and snippets.

@tzengerink
Last active October 7, 2015 10:37
Show Gist options
  • Save tzengerink/3151443 to your computer and use it in GitHub Desktop.
Save tzengerink/3151443 to your computer and use it in GitHub Desktop.
PubSub.js
/*!
* PubSub.js
* ---------
*
* Extremely basic PubSub functionality.
*
* To subscribe to the topic `news`:
*
* PubSub.on("news", function(str){
* alert(str);
* });
*
* To publish the topic `news`:
*
* PubSub.trigger("news", "Extra extra!");
*
* To unsubscribe from the topic `news`:
*
* PubSub.off("news");
*
* Copyright (c) 2013, T. Zengerink
* Licensed under MIT License.
* See: https://gist.github.com/raw/3151357/6806e68cb9cc0042b265f25be9bc25dd39f75267/LICENSE.md
*/
var PubSub = (function(){
pubsub = {},
subscriptions = {};
// Unsubscribe
pubsub.off = function( topic ){
subscriptions[topic] = [];
};
// Subscribe
pubsub.on = function( topic, fn ){
if (typeof subscriptions[topic] === "undefined") {
subscriptions[topic] = [];
}
subscriptions[topic].push(fn);
};
// Publish
pubsub.trigger = function( topic, args ){
for (t in subscriptions[topic]) {
typeof subscriptions[topic][t] === "function" && subscriptions[topic][t](args);
}
};
return pubsub;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment