Last active
October 7, 2015 10:37
-
-
Save tzengerink/3151443 to your computer and use it in GitHub Desktop.
PubSub.js
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
/*! | |
* 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