Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | 4x 10x 5x 18x 2x 2x 2x 6x 6x 2x | import {DefaultMap} from '../map/default-map';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EventCallback = (...args: any[]) => void;
export interface EventDispatcher {
/**
* Adds a callback that will be run each time the event is dispatched.
*
* Adding the same event/callback pair a second time should have no effect.
*/
on(event: string, callback: EventCallback | Function): void;
/**
* Stops the callback from being run each time the event is dispatched.
*/
off(event: string, callback: EventCallback | Function): void;
}
/**
* Utility class to simplify implementation of the EventDispatcher interface.
*
* Example:
* ```
* class Foo implements EventDispatcher {
* private eventManager: EventManager;
* constructor() {
* this.eventManager = new EventManager();
* }
*
* on(event: string, callback: Function) {
* this.eventManager.on(event, callback);
* }
*
* off(event: string, callback: Function) {
* this.eventManager.off(event, callback);
* }
*
* bar() {
* this.eventManager.dispatch('someEvent');
* }
* }
* ```
*/
export class EventManager {
private callbacks: DefaultMap<string, Set<EventCallback | Function>>;
constructor() {
this.callbacks = DefaultMap.usingFunction(
() => new Set<EventCallback | Function>()
);
}
/**
* Run the given callback when the given event is dispatched.
*/
on(event: string, callback: EventCallback | Function): void {
this.callbacks.get(event).add(callback);
}
/**
* Run callbacks for the given event with the given arguments.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
dispatch(event: string, ...args: any[]): void {
this.callbacks.get(event).forEach((callback) => callback(...args));
}
/**
* Stop running the given callback on the given event.
*/
off(event: string, callback: EventCallback | Function): void {
const callbacks = this.callbacks.get(event);
callbacks.delete(callback);
if (callbacks.size === 0) {
this.callbacks.delete(event);
}
}
/**
* Clear out internal Sets and Map.
*/
dispose(): void {
const values = this.callbacks.values();
let callbackSet = values.next();
while (!callbackSet.done) {
callbackSet.value.clear();
callbackSet = values.next();
}
this.callbacks.clear();
}
}
|