|
| 1 | +import { EventsRecord } from "./EventEmittingComponent"; |
| 2 | +import { EventEmitter } from "./EventEmitter"; |
| 3 | + |
| 4 | +/** |
| 5 | + * Event Emitter variant that emits a certain event only once to a registered listener. |
| 6 | + * Additionally, if a listener registers to a event that has already been emitted, it |
| 7 | + * re-emits it to said listener. |
| 8 | + * This pattern is especially useful for listening for inclusions of transactions. |
| 9 | + * Those events will only occur once, and listeners could come too late to the party, |
| 10 | + * so we need to make sure they get notified as well in those cases. |
| 11 | + */ |
| 12 | +export class ReplayingSingleUseEventEmitter< |
| 13 | + Events extends EventsRecord, |
| 14 | +> extends EventEmitter<Events> { |
| 15 | + public emitted: Partial<Events> = {}; |
| 16 | + |
| 17 | + public emit<Key extends keyof Events>( |
| 18 | + event: Key, |
| 19 | + ...parameters: Events[Key] |
| 20 | + ) { |
| 21 | + super.emit(event, ...parameters); |
| 22 | + this.emitted[event] = parameters; |
| 23 | + this.listeners[event] = []; |
| 24 | + } |
| 25 | + |
| 26 | + public onAll(listener: (event: keyof Events, args: unknown[]) => void) { |
| 27 | + Object.entries(this.emitted).forEach(([key, params]) => { |
| 28 | + if (params !== undefined) listener(key, params); |
| 29 | + }); |
| 30 | + super.onAll(listener); |
| 31 | + } |
| 32 | + |
| 33 | + public on<Key extends keyof Events>( |
| 34 | + event: Key, |
| 35 | + listener: (...args: Events[Key]) => void |
| 36 | + ) { |
| 37 | + if (this.emitted[event] !== undefined) { |
| 38 | + listener(...this.emitted[event]!); |
| 39 | + } |
| 40 | + super.on(event, listener); |
| 41 | + } |
| 42 | +} |
0 commit comments