Last active
August 29, 2015 13:55
-
-
Save tastywheat/f064c21970b7ffa28283 to your computer and use it in GitHub Desktop.
pubsub.js
This file contains 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 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