packageDocumentation module import { UnexpectedErrors } from "./UnexpectedErrors" ; public export type Listener = ( ... arg : any [ ] ) => void ; interface EventContext { listener : Listener | undefined ; scope : any ; once : boolean ; } public export class BeEvent < T extends Listener > { private _listeners : EventContext [ ] = [ ] ; private _insideRaiseEvent : boolean = false ; /** The number of listeners currently subscribed to the event. */ public get numberOfListeners ( ) { return this . _listeners . length ; } param listener param scope returns see public addListener ( listener , scope ? ) { this . _listeners . push ( { listener , scope , once : false } ) ; return ( ) => this . removeListener ( listener , scope ) ; } param listener param scope returns see public addOnce ( listener , scope ? ) { this . _listeners . push ( { listener , scope , once : true } ) ; return ( ) => this . removeListener ( listener , scope ) ; } param listener param scope returns see public removeListener ( listener , scope ? ) { const listeners = this . _listeners ; for ( let i = 0 ; i < listeners . length ; ++ i ) { const context = listeners [ i ] ; if ( context . listener === listener && context . scope === scope ) { if ( this . _insideRaiseEvent ) { context . listener = undefined ; } else { listeners . splice ( i , 1 ) ; } return true ; } } return false ; } param args see public raiseEvent ( ... args ) { this . _insideRaiseEvent = true ; const listeners = this . _listeners ; const length = listeners . length ; let dropped = false ; for ( let i = 0 ; i < length ; ++ i ) { const context = listeners [ i ] ; if ( ! context . listener ) { dropped = true ; } else { try { context . listener . apply ( context . scope , args ) ; } catch ( e ) { UnexpectedErrors . handle ( e ) ; } if ( context . once ) { context . listener = undefined ; dropped = true ; } } } if ( dropped ) this . _listeners = this . _listeners . filter ( ( ctx ) => ctx . listener !== undefined ) ; this . _insideRaiseEvent = false ; } param listener param scope public has ( listener , scope ? ) { for ( const ctx of this . _listeners ) { if ( ctx . listener === listener && ctx . scope === scope ) { return true ; } } return false ; } /** Clear all Listeners from this BeEvent. */ public clear ( ) { this . _listeners . length = 0 ; } } public export class BeUiEvent < TEventArgs > extends BeEvent < ( args : TEventArgs ) => void > { /** Raises event with single strongly typed argument. */ public emit ( args ) { this . raiseEvent ( args ) ; } } public export class BeEventList < T extends Listener > { private _events : { [ name ] : BeEvent < T > | undefined ; } = { } ; param name public get ( name ) { let event = this . _events [ name ] ; if ( event ) return event ; event = new BeEvent ( ) ; this . _events [ name ] = event ; return event ; } param name public remove ( name ) { this . _events [ name ] = undefined ; } }