Skip to content

Instantly share code, notes, and snippets.

@arnorhs
Forked from 140bytes/LICENSE.txt
Last active December 15, 2015 15:09
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 arnorhs/5279954 to your computer and use it in GitHub Desktop.
Save arnorhs/5279954 to your computer and use it in GitHub Desktop.
function(
l, // this will actually be where the events will be stored
u, // placeholder for undefined
r, // placeholder for the current array of events
i // placeholder for the index in the array loop
){
// the returned function takes either a name + variably sized arguments, or a name and an event handler
return function(n,f){
// assign the selected object, and store a shorter version, and assign i for the start of the loop
r=l[n]=l[n]||[],i=-1;
// if the second argument has a call method, we assume this is a subscribe call
if(f&&f.call)r.push(f);
// loop through each subscribed function and call the method with the current arguments
else while(r[++i])r[i].apply(u,arguments);
}
}({})
function(l,u,r,i){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);}}({})
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Arnor Sigurdsson <arnorhs@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "simplePublishSubscribeLibrary",
"description": "A fully fledged flexible publish/subscribe library",
"keywords": [
"events",
"publish",
"subscribe",
"meta",
"javascript"
]
}
<!DOCTYPE html>
<title>publish/subscribe lib in less than 140 characters</title>
<script>
var pubsub = function(l,u,r,i){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");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment