Created
January 4, 2021 00:16
-
-
Save bramaudi/fdcf0203c888fc4ca9771fc45bf9d4b9 to your computer and use it in GitHub Desktop.
Native Javascript EventBus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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