Skip to content

Instantly share code, notes, and snippets.

@PierfrancescoSoffritti
Last active February 15, 2024 14:16
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save PierfrancescoSoffritti/6f22d1e799e4877d7864c0df3dffb6d7 to your computer and use it in GitHub Desktop.
Save PierfrancescoSoffritti/6f22d1e799e4877d7864c0df3dffb6d7 to your computer and use it in GitHub Desktop.
A simple implementation of an event bus in Javascript. More details here: https://medium.com/@soffritti.pierfrancesco/create-a-simple-event-bus-in-javascript-8aa0370b3969
/**
* subscriptions data format:
* { eventType: { id: callback } }
*/
const subscriptions = { }
const getNextUniqueId = getIdGenerator()
function subscribe(eventType, callback) {
const id = getNextUniqueId()
if(!subscriptions[eventType])
subscriptions[eventType] = { }
subscriptions[eventType][id] = callback
return {
unsubscribe: () => {
delete subscriptions[eventType][id]
if(Object.keys(subscriptions[eventType]).length === 0) delete subscriptions[eventType]
}
}
}
function publish(eventType, arg) {
if(!subscriptions[eventType])
return
Object.keys(subscriptions[eventType]).forEach(key => subscriptions[eventType][key](arg))
}
function getIdGenerator() {
let lastId = 0
return function getNextUniqueId() {
lastId += 1
return lastId
}
}
module.exports = { publish, subscribe }
@ideafm
Copy link

ideafm commented Apr 24, 2019

Nice! What about using Symbol instead of ID generator, as suggested here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment