Created
May 1, 2020 16:21
-
-
Save Loonz806/367b15136c27568f8581f0df3bac08c5 to your computer and use it in GitHub Desktop.
Pubsub pattern
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
let subscribers = {}; | |
module.exports = { | |
// method to publish an update | |
publish(event, data) { | |
if (!subscribers[event]) return; | |
subscribers[event].forEach(subscriberCallback => | |
subscriberCallback(data)); | |
}, | |
// method to subscribe an update | |
subscribe(event, callback) { | |
let index; | |
if (!subscribers[event]) { | |
subscribers[event] = []; | |
} | |
index = subscribers[event].push(callback) - 1; | |
return { | |
unsubscribe() { | |
subscribers[event].splice(index, 1); | |
} | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment