Created
August 19, 2016 07:28
-
-
Save JeffreyBPetersen/5399848ecf2a50264faa2ebdfc82ba10 to your computer and use it in GitHub Desktop.
Simple publisher/subscriber design pattern in javascript.
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
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