Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.