import { Events } from './events' ; export class Emitter < EventTypes > { events : { [ key ] : Function [ ] ; } = { } ; silent = false ; constructor ( events ) { this . events = events instanceof Emitter ? events . events : events . handlers ; } on < K extends keyof EventTypes > ( names , handler ) { const events = names instanceof Array ? names : ( names as string ) . split ( ' ' ) ; ( events as string [ ] ) . forEach ( name => { if ( ! this . events [ name ] ) throw new Error ( `The event ${ name } does not exist` ) ; this . events [ name ] . push ( handler ) ; } ) ; return this ; } trigger < K extends keyof EventTypes > ( name , params = { } ) { if ( ! ( name in this . events ) ) throw new Error ( `The event ${ name } cannot be triggered` ) ; return this . events [ name as string ] . reduce ( ( r , e ) => { return ( e ( params ) !== false ) && r ; } , true ) ; } bind ( name ) { if ( this . events [ name ] ) throw new Error ( `The event ${ name } is already bound` ) ; this . events [ name ] = [ ] ; } exist ( name ) { return Array . isArray ( this . events [ name ] ) ; } }