Skip to content

Instantly share code, notes, and snippets.

@frockenstein
Created March 8, 2012 15:53
Show Gist options
  • Save frockenstein/2001636 to your computer and use it in GitHub Desktop.
Save frockenstein/2001636 to your computer and use it in GitHub Desktop.
JS: Global Pub Sub
var global = {
// pub sub lifted from http://jsperf.com/pub-sub-implementations/13
cache: {},
publish: function(topic, args) {
var self = this;
if (self.cache[topic]) {
var currentCache = self.cache[topic],
currentArgs = args || [];
// make sure currentAgs is an array
if (!$.isArray(currentArgs)) currentArgs = $.makeArray(currentArgs);
for (var i = 0, j = currentCache.length; i < j; i++) {
var callback = currentCache[i][0],
context = currentCache[i][1];
callback.apply(context, currentArgs);
}
}
},
subscribe: function(topic, callback, context) {
var self = this;
context = context || $;
if (!self.cache[topic]) {
self.cache[topic] = [];
}
self.cache[topic].push([callback, context]);
return [topic, callback, context];
},
unsubscribe: function(handle) {
var self = this;
var topic = handle[0];
if (self.cache[topic]) {
var currentCache = self.cache[topic];
for (var i = 0, j = currentCache.length; i < j; i++) {
if (currentCache[i] === handle[1]) {
currentCache.splice(i, 1);
}
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment