Last active
          February 3, 2023 13:16 
        
      - 
      
- 
        Save olsgreen/bf49fb733668c8190e40dc415371ff7e to your computer and use it in GitHub Desktop. 
    Minimal javascript event bus
  
        
  
    
      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 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