Last active
June 22, 2020 03:42
-
-
Save deanacus/d6fb60b28334dba9d4da2ba95617101e to your computer and use it in GitHub Desktop.
Simple PubSub implementation
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
const pubSub = () => { | |
// The core of our pubsub implementation | |
const subscriptions = {} | |
// Stupid naive way to generate an ID for each subscription. | |
// Should really be something more robust, but this is a simple implementation after all | |
const generateID = () => Math.floor(Math.random() * 100); | |
// Publish handler. Runs all the callbacks for a given eventName | |
const publish = (eventName, data) => subscriptions[eventName] && subscriptions[eventName].map(subscription => subscription.callback(...data)); | |
// Subscribe Handler. Adds a subscriber for an event, with an ID so we can unsubscribe each unique subscriber | |
const subscribe = (eventName, callback) => { | |
const eventID = generateID(); | |
// If there's no existing subscriptions, create an empty array for it. | |
if(!subscriptions[eventName]) { | |
subscriptions[eventName] = [] | |
} | |
// Push the subscriber to the event array | |
subscriptions[eventName].push({id: eventID, callback}); | |
// Return an unsubscribe function. | |
return () => subscriptions[eventName] = subscriptions[eventName].filter(event => event.id !== eventID) | |
} | |
// Method for clearing all subscribers from an event | |
const clearSubscribers = (eventName) => subscriptions[eventName] = [] | |
return { | |
publish, | |
subscribe, | |
clearSubscribers, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment