import { Is } from '../misc/Is' ; import { nullishToEmptyArray } from '../misc/MiscUtil' ; export type EventType = string | symbol ; export type EventSubscriberIndex = number ; export type CalledSubscriberNumber = number ; export type EventHandler = ( event : unknown ) => void ; export interface IEventPubSub { subscribe ( type , handler ) : EventSubscriberIndex ; unsubscribe ( type , index ) : void ; unsubscribeAll ( type , handler ) : void ; publishAsync ( type , event ? ) : CalledSubscriberNumber ; publishSync ( type , event ? ) : CalledSubscriberNumber ; } export class EventPubSub implements IEventPubSub { private __subscriberMap : Map < EventType , EventHandler [ ] > = new Map ( ) ; subscribe ( type , handler ) { let subscribers = this . __subscriberMap . get ( type ) ; if ( Is . not . exist ( subscribers ) ) { this . __subscriberMap . set ( type , [ ] ) ; subscribers = this . __subscriberMap . get ( type ) ; } return subscribers ! . push ( handler ) - 1 ; } unsubscribe ( type , index ) { const subscribers = this . __subscriberMap . get ( type ) ; if ( subscribers == null ) { return ; } subscribers . splice ( index , 1 ) ; } unsubscribeAll ( type ) { this . __subscriberMap . delete ( type ) ; } publishAsync ( type , event ? ) { let count = 0 ; const subscribers = nullishToEmptyArray ( this . __subscriberMap . get ( type ) ) ; for ( const sub of subscribers ) { setTimeout ( sub . bind ( this , event ) , 0 ) ; count ++ ; } return count ; } publishSync ( type , event ? ) { let count = 0 ; const subscribers = nullishToEmptyArray ( this . __subscriberMap . get ( type ) ) ; for ( const sub of subscribers ) { sub ( event ) ; count ++ ; } return count ; } }