Skip to content

Instantly share code, notes, and snippets.

@Loonz806
Created May 1, 2020 16:21
Show Gist options
  • Save Loonz806/367b15136c27568f8581f0df3bac08c5 to your computer and use it in GitHub Desktop.
Save Loonz806/367b15136c27568f8581f0df3bac08c5 to your computer and use it in GitHub Desktop.
Pubsub pattern
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