Skip to content

Instantly share code, notes, and snippets.

@pwFoo
Forked from sivagao/minimal_pubsub.js
Created July 31, 2023 06:33
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 pwFoo/8011cdbf8f4719d13e89c698e264c446 to your computer and use it in GitHub Desktop.
Save pwFoo/8011cdbf8f4719d13e89c698e264c446 to your computer and use it in GitHub Desktop.
minimal pubsub js
var pubsub = function(l, u, r, i) { // cool! 闭包并且初始化vars
return function(n, f) {
r = l[n] = l[n] || [], i = -1;
if (f && f.call) r.push(f);
else while (r[++i]) r[i].apply(u, arguments);
}
}({});
// subscribe to event
pubsub("eat_cookie", function() {
alert("Cookie was eaten");
});
// subscribe to another event which expects arguments
pubsub("bake_cake", function(name, arg1, arg2) {
alert("Making a cake from " + arg1 + " and " + arg2);
});
pubsub("bake_cake", function(name, arg1, arg2) {
alert("I don't like baking but if I'd bake I'd use " + arg1 + " and " + arg2);
});
// trigger events
pubsub("eat_cookie");
pubsub("bake_cake", "eggs", "sugar");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment