Skip to content

Instantly share code, notes, and snippets.

@nicholasbs
Created July 27, 2012 17:08
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 nicholasbs/3189198 to your computer and use it in GitHub Desktop.
Save nicholasbs/3189198 to your computer and use it in GitHub Desktop.
Super simple "pub-sub" code
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