Skip to content

Instantly share code, notes, and snippets.

@mvsde
Last active June 30, 2021 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvsde/2c9c43cbe09f284b2bfc88a4d2bbda8b to your computer and use it in GitHub Desktop.
Save mvsde/2c9c43cbe09f284b2bfc88a4d2bbda8b to your computer and use it in GitHub Desktop.
Subscribe / Publish pattern
/**
* 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