- 
      
 - 
        
Save rosputniy/cba1b0dba1e5920878e7bb617f2cee08 to your computer and use it in GitHub Desktop.  
    A simple implementation of an event bus in Javascript
  
        
  
    
      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
    
  
  
    
  | function EventBus() { | |
| const eventCallbacksPairs = []; | |
| this.subscribe = function( eventType, callback ) { | |
| const eventCallbacksPair = findEventCallbacksPair(eventType); | |
| if(eventCallbacksPair) | |
| eventCallbacksPair.callbacks.push(callback); | |
| else | |
| eventCallbacksPairs.push( new EventCallbacksPair(eventType, callback) ); | |
| } | |
| this.post = function( eventType, args ) { | |
| const eventCallbacksPair = findEventCallbacksPair(eventType); | |
| if(!eventCallbacksPair) { | |
| console.error("no subscribers for event " +eventType); | |
| return; | |
| } | |
| eventCallbacksPair.callbacks.forEach( callback => callback(args) ); | |
| } | |
| function findEventCallbacksPair(eventType) { | |
| return eventCallbacksPairs.find( eventObject => eventObject.eventType === eventType ); | |
| } | |
| function EventCallbacksPair( eventType, callback ) { | |
| this.eventType = eventType; | |
| this.callbacks = [callback]; | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment