Skip to content

Instantly share code, notes, and snippets.

@bramaudi
Created January 4, 2021 00:16
Show Gist options
  • Select an option

  • Save bramaudi/fdcf0203c888fc4ca9771fc45bf9d4b9 to your computer and use it in GitHub Desktop.

Select an option

Save bramaudi/fdcf0203c888fc4ca9771fc45bf9d4b9 to your computer and use it in GitHub Desktop.
Native Javascript EventBus
export default class EventBus {
__eventTarget
constructor(description = '') {
this.__eventTarget = document.appendChild(document.createComment(description))
}
/**
* Add event
* @param {String} type
* @param {(event: CustomEvent<DetailType>) => void} listener
* @param {Boolean} render
*/
on(type, listener) {
this.__eventTarget.addEventListener(type, listener)
}
/**
* Add event once
* @param {String} type
* @param {(event: CustomEvent<DetailType>) => void} listener
*/
once(type, listener) {
this.__eventTarget.addEventListener(type, listener, { once: true })
}
/**
* Remove event
* @param {String} type
* @param {(event: CustomEvent<DetailType>) => void} listener
*/
off(type, listener) {
this.__eventTarget.removeEventListener(type, listener)
}
/**
* Emit/trigger event
* @param {String} type
* @param {any} detail
*/
emit(type, detail = null) {
return this.__eventTarget.dispatchEvent(
new CustomEvent(type, { detail })
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment