Last active
June 30, 2021 07:52
-
-
Save mvsde/2c9c43cbe09f284b2bfc88a4d2bbda8b to your computer and use it in GitHub Desktop.
Subscribe / Publish 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
/** | |
* Use Mitt instead: https://github.com/developit/mitt | |
*/ | |
const EventBus = { | |
topics: {}, | |
subscribe: function (topic, listener) { | |
// Create topic if not yet created | |
if (!this.topics[topic]) { | |
this.topics[topic] = [] | |
} | |
// Add topic listener | |
this.topics[topic].push(listener) | |
}, | |
publish: function (topic, data) { | |
// Return if the topic doesn't exist | |
// or if there are no listeners | |
if (!this.topics[topic] || this.topics[topic].length < 1) { | |
return | |
} | |
// Send event to all listeners | |
this.topics[topic].forEach(listener => { | |
listener(data || {}) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment