Created
April 2, 2013 10:02
-
-
Save sivagao/5291190 to your computer and use it in GitHub Desktop.
minimal pubsub js
This file contains hidden or 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
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