Skip to content

Instantly share code, notes, and snippets.

@olsgreen
Last active February 3, 2023 13:16
Show Gist options
  • Save olsgreen/bf49fb733668c8190e40dc415371ff7e to your computer and use it in GitHub Desktop.
Save olsgreen/bf49fb733668c8190e40dc415371ff7e to your computer and use it in GitHub Desktop.
Minimal javascript event bus
export class Events {
bus: HTMLElement
constructor() {
this.bus = document.createElement('div')
}
on(event: string, callback: Function) {
this.bus.addEventListener(event, callback as EventListenerOrEventListenerObject)
}
off(event: string, callback: Function) {
this.bus.removeEventListener(event, callback as EventListenerOrEventListenerObject)
}
emit(event: string, payload = {}) {
this.bus.dispatchEvent(new CustomEvent(event, {
detail: payload
}))
}
}
export const Bus = new Events()
export default Bus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment