Created
July 27, 2012 17:08
-
-
Save nicholasbs/3189198 to your computer and use it in GitHub Desktop.
Super simple "pub-sub" code
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
REGISTRY = {} | |
function sub (name, cb, ctx) { | |
if (typeof REGISTRY[name] === "undefined") { | |
REGISTRY[name] = []; | |
} | |
return REGISTRY[name].push({cb: cb, ctx: ctx || null}); | |
} | |
function pub (name) { | |
var subscribers = REGISTRY[name] || []; | |
for (var i=0; i<subscribers.length; i++) { | |
subscribers[i].cb.call(subscribers[i].ctx); | |
} | |
return subscribers.length; | |
} | |
/* Example usage */ | |
sub("hello", function () { console.log("I got hello!"); }); | |
sub("hello", function () { console.log("I also got hello!"); }); | |
sub("bye", function () { console.log("I got bye!"); }); | |
pub("hello"); | |
pub("bye"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment