import { HandlerMapErrors } from "./Errors" ; import { EventDispatcher } from "./EventDispatcher" ; import { Handle } from "./Handle" ; export class HandleMap < T extends Handle > { protected _data = new Map < string , T > ( ) ; protected _ctor : { new ( ... args ) : T ; } ; protected _onChange = new EventDispatcher < ( name : string , item ? : T ) => void > ( ) ; constructor ( ctor ) { this . _ctor = ctor ; } public watch ( fn ) { this . _onChange . on ( fn ) ; } public unwatch ( fn ) { this . _onChange . off ( fn ) ; } public create ( name ) { const handler = this . factoryHook ( ) ; this . set ( name , handler ) ; return handler ; } public set ( name , handler ) { if ( this . _data . has ( name ) ) { throw HandlerMapErrors . ALREADY_EXISTS ( name ) ; } this . _data . set ( name , handler ) ; this . emitChange ( name , handler ) ; } public get ( name ) { return this . _data . get ( name ) ; } public dispose ( name ? ) { if ( ! name ) { const promises = [ ] ; this . _data . forEach ( ( item , key ) => { this . emitChange ( key , undefined ) ; const p = this . disposeHook ( item ) ; promises . push ( p ) ; } ) ; this . _data . clear ( ) ; return Promise . all ( promises ) . then ( ( ) => Promise . resolve ( ) ) ; } const handler = this . _data . get ( name ) ; if ( handler ) { this . emitChange ( name , undefined ) ; const p = this . disposeHook ( handler ) ; this . _data . delete ( name ) ; return p ; } return Promise . resolve ( ) ; } protected disposeHook ( handler ) { return handler . dispose ( ) ; } protected factoryHook ( ) { return new this . _ctor ( ) ; } protected emitChange ( name , handler ? ) { return this . _onChange . listeners . map ( fn => fn ( name , handler ) ) ; } }