Created
March 8, 2012 15:53
-
-
Save frockenstein/2001636 to your computer and use it in GitHub Desktop.
JS: Global Pub Sub
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
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