| 10 | } |
| 11 | |
| 12 | export class EventEmitter<TEvent, TResult = unknown> implements Disposable { |
| 13 | protected readonly listeners: EventListenerInfo<TEvent, TResult>[] = []; |
| 14 | |
| 15 | constructor() { |
| 16 | this.event = this.event.bind(this); |
| 17 | } |
| 18 | |
| 19 | protected addEventListener( |
| 20 | info: EventListenerInfo<TEvent, TResult>, |
| 21 | ): RemoveEventListener { |
| 22 | this.listeners.push(info); |
| 23 | |
| 24 | const remove: RemoveEventListener = () => { |
| 25 | const index = this.listeners.indexOf(info); |
| 26 | if (index !== -1) { |
| 27 | this.listeners.splice(index, 1); |
| 28 | } |
| 29 | }; |
| 30 | remove.dispose = remove; |
| 31 | return remove; |
| 32 | } |
| 33 | |
| 34 | event: Event<TEvent, TResult> = <TThis, TArgs extends unknown[]>( |
| 35 | listener: EventListener<TEvent, TThis, TArgs, TResult>, |
| 36 | thisArg?: TThis, |
| 37 | ...args: TArgs |
| 38 | ) => { |
| 39 | const info: EventListenerInfo<TEvent, TResult> = { |
| 40 | listener: listener as EventListener< |
| 41 | TEvent, |
| 42 | unknown, |
| 43 | unknown[], |
| 44 | TResult |
| 45 | >, |
| 46 | thisArg, |
| 47 | args, |
| 48 | }; |
| 49 | return this.addEventListener(info); |
| 50 | }; |
| 51 | |
| 52 | fire(e: TEvent) { |
| 53 | for (const info of this.listeners.slice()) { |
| 54 | info.listener.call(info.thisArg, e, ...info.args); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | dispose() { |
| 59 | this.listeners.length = 0; |
| 60 | } |
| 61 | } |
nothing calls this directly
no test coverage detected