Skip to content

Instantly share code, notes, and snippets.

@gahabeen
Created June 29, 2020 20:16
Show Gist options
  • Save gahabeen/c3d2446d9aa1704f267d5a09e989bfa3 to your computer and use it in GitHub Desktop.
Save gahabeen/c3d2446d9aa1704f267d5a09e989bfa3 to your computer and use it in GitHub Desktop.
EventBus - Vanilla JS
class EventBus {
registry = new Map()
constructor() {}
on(type, handler) {
const handlers = this.registry.get(type)
const added = handlers && handlers.push(handler)
if (!added) {
this.registry.set(type, [handler])
}
}
off(type, handler) {
const handlers = this.registry.get(type)
const handlerIndex = handlers.indexOf(handler)
if (handlers && handlerIndex > -1) {
handlers.splice(handlerIndex, 1)
}
}
emit(type, payload) {
this.registry
.get(type)
.slice()
.map((handler) => handler(payload))
}
}
const bus = new EventBus()
function test(p) {
console.log('test!', payload)
}
bus.on('test', test)
bus.on('test1', (payload) => console.log('test 1!', payload))
bus.off('test', test)
bus.emit('test1')
bus.emit('test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment