import { MessageRunner } from "./MessageRunner" ; import { safelyCallBack } from "./safelyCallBack" ; /**
 * Message Dispatcher implementation.
 */ export class MessageDispatcher { private _handlers : Map < string , Function [ ] > = new Map ( ) ; param message param handler public addMessageHandler ( message , handler ) { let messageHandlers = this . _handlers . get ( message ) ; if ( messageHandlers ) { if ( messageHandlers . indexOf ( handler ) === - 1 ) { messageHandlers . push ( handler ) ; } } else { this . _handlers . set ( message , [ handler ] ) ; } } param message return public hasMessageHandler ( message ) { return this . _handlers . has ( message ) ; } param message param handler public removeMessageHandler ( message , handler ) { let messageHandlers = this . _handlers . get ( message ) ; let index = messageHandlers ? messageHandlers . indexOf ( handler ) : - 1 ; if ( index !== - 1 ) { messageHandlers . splice ( index , 1 ) ; if ( messageHandlers . length === 0 ) { this . _handlers . delete ( message ) ; } } } param message param callback param reverse public dispatchMessage ( message , callback = null , reverse = false ) { let handlers = this . _handlers . get ( < any > message ) ; if ( handlers ) { handlers = handlers . concat ( ) ; if ( ! reverse ) { handlers . reverse ( ) ; } new MessageRunner ( message , handlers , callback ) . run ( ) ; } else { if ( callback ) { safelyCallBack ( callback ) ; } } } }