Skip to content

Instantly share code, notes, and snippets.

@craveytrain
Created October 1, 2010 03:56
Show Gist options
  • Save craveytrain/605701 to your computer and use it in GitHub Desktop.
Save craveytrain/605701 to your computer and use it in GitHub Desktop.
Resilient Pub/Sub
;(function($){
var cache = {};
$.pub = function (topic, args) {
cache[topic] && $.each(cache[topic], function () {
try {
this.apply($, args || []);
} catch (e) {
if (console) console.warn(e);
}
});
};
$.sub = function (topic, callback) {
if(!cache[topic]){
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback];
};
$.unsub = function (handle) {
var t = handle[0];
cache[t] && $.each(cache[t], function (i) {
if (this === handle[1]) {
cache[t].splice(i, 1);
}
});
};
})(jQuery);
function callMe () {
for (var i = 0, l = arguments.length; i < l; i++) {
console.log(arguments[i]);
}
DOES_NOT_EXIST++;
}
function callMe2 () {
console.log('hi');
DOES_NOT_EXIST++;
}
$.sub('test', callMe);
var removeMe = $.sub('test', callMe2);
$.pub('test', ['Init: 1']);
$.pub('test', ['Init: 2', 'Init: 3']);
$.unsub(removeMe);
$.pub('test', ['Init: 4', 'Init: 5']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment