Skip to content

Instantly share code, notes, and snippets.

@andrewimm
Created June 27, 2012 20:27
Show Gist options
  • Save andrewimm/3006678 to your computer and use it in GitHub Desktop.
Save andrewimm/3006678 to your computer and use it in GitHub Desktop.
Playing JS Golf with PubSub. 171 bytes gzipped
function ps(d){c={};d.pub=function(a,b){for(var i=c[a].length;i;)c[a][--i].apply(this,b)};d.sub=function(a,b){c[a]?c[a].push(b):c[a]=[b]};d.unsub=function(a,b){c[a]=(c[a]||[]).filter(function(i){return i!==b})}}
@andrewimm
Copy link
Author

ps() adds pub/sub/unsub methods to any object.
For instance: ps(window);
After this, window.sub(channel, function) sets function to be called whenever data is published to channel,
window.pub(channel, values) applies the array values of values as the arguments of each callback on channel,
and window.unsub(channel, function) removes function from the list of methods subscribed to channel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment