Skip to content

Instantly share code, notes, and snippets.

@tastywheat
Last active August 29, 2015 13:55
Show Gist options
  • Save tastywheat/f064c21970b7ffa28283 to your computer and use it in GitHub Desktop.
Save tastywheat/f064c21970b7ffa28283 to your computer and use it in GitHub Desktop.
pubsub.js
var App = {};
App.cache = {};
App.uniqueId = 0;
App.publish = function(channel, data){
for(var index in App.cache[channel])
App.cache[channel][index](data);
}
App.subscribe = function(channel, handler){
if(!App.cache[channel])
App.cache[channel] = {};
App.cache[channel][App.uniqueId] = handler;
return App.uniqueId++;
}
App.unsubscribe = function(channel, id){
delete App.cache[channel][id];
}
/* Usage
var handlerId = App.subscribe('brianchannel', function(message){ console.log(message); })
App.publish('brianchannel', 'brian is the best')
App.unsubscribe('brianchannel', handlerId);
*/
/* OUTPUT
brian is the best
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment