Skip to content

Instantly share code, notes, and snippets.

@JeffreyBPetersen
Created August 19, 2016 07:28
Show Gist options
  • Save JeffreyBPetersen/5399848ecf2a50264faa2ebdfc82ba10 to your computer and use it in GitHub Desktop.
Save JeffreyBPetersen/5399848ecf2a50264faa2ebdfc82ba10 to your computer and use it in GitHub Desktop.
Simple publisher/subscriber design pattern in javascript.
function PubSub(){
this.channels = {};
this.channelBySubscription = {};
this.nextSubscriptionID = 0;
};
PubSub.prototype.pub = function(channel, publication){
let currentChannel = this.channels[channel];
for(let subscriptionID in currentChannel){
currentChannel[subscriptionID](publication);
}
};
PubSub.prototype.sub = function(channel, subscriber){
if(!this.channels[channel]) this.channels[channel] = {};
let subscriptionID = this.nextSubscriptionID++;
this.channels[channel][subscriptionID] = subscriber;
this.channelBySubscription[subscriptionID] = channel;
return subscriptionID;
};
PubSub.prototype.unsub = function(subscriptionID){
delete this.channels[this.channelBySubscription[subscriptionID]][subscriptionID];
};
// example
(() => {
console.log(document.body.innerText);
pubsub = new PubSub();
setInterval(() => pubsub.pub('cry', 'wolf!'), 1000);
let subscription = pubsub.sub('cry', data => console.log(`someone cried ${data}`));
setTimeout(() => pubsub.unsub(subscription), 5000);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment