Skip to content

Instantly share code, notes, and snippets.

@EyePulp
Forked from fatihacet/pubsub-simple.js
Last active August 29, 2015 13:57
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 EyePulp/9817388 to your computer and use it in GitHub Desktop.
Save EyePulp/9817388 to your computer and use it in GitHub Desktop.
define([], function() {
/* See also: "Learning Javascript Design Patterns" by Addy Osmani
* http://addyosmani.com/resources/essentialjsdesignpatterns/book/
*
* for examples on how to use pubsub as event aggregator (Mediator)
*
*/
var pubsub = function(){};
(function(q) {
var topics = {}, subUid = -1;
q.subscribe = function(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
q.publish = function(topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
q.unsubscribe = function(token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
}(pubsub));
return pubsub;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment