2016-03-13 11:28:29 +01:00
|
|
|
export class Event<T> {
|
2020-01-03 11:36:39 +01:00
|
|
|
protected handlers: ((data?: T) => void)[] = [];
|
|
|
|
protected singleHandlers: ((data?: T) => void)[] = [];
|
2016-03-13 11:28:29 +01:00
|
|
|
|
2020-01-03 11:36:39 +01:00
|
|
|
public on(handler: (data?: T) => void): void {
|
2022-04-04 19:37:31 +02:00
|
|
|
if (typeof handler !== 'function') {
|
2020-01-03 11:36:39 +01:00
|
|
|
throw new Error('Event::on: Handler is not a function');
|
2016-03-13 11:28:29 +01:00
|
|
|
}
|
2017-06-10 22:32:56 +02:00
|
|
|
this.handlers.push(handler);
|
|
|
|
}
|
2016-03-13 11:28:29 +01:00
|
|
|
|
2020-01-03 11:36:39 +01:00
|
|
|
public once(handler: (data?: T) => void): void {
|
2022-04-04 19:37:31 +02:00
|
|
|
if (typeof handler !== 'function') {
|
2020-01-03 11:36:39 +01:00
|
|
|
throw new Error('Event::once: Handler is not a function');
|
|
|
|
}
|
|
|
|
this.singleHandlers.push(handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
public wait(): Promise<void> {
|
|
|
|
return new Promise<void>((resolve) => {
|
|
|
|
this.once(() => {
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public off(handler: (data?: T) => void): void {
|
2022-04-04 19:37:31 +02:00
|
|
|
this.handlers = this.handlers.filter((h) => h !== handler);
|
|
|
|
this.singleHandlers = this.singleHandlers.filter((h) => h !== handler);
|
2017-06-10 22:32:56 +02:00
|
|
|
}
|
2016-03-13 11:28:29 +01:00
|
|
|
|
2020-01-03 11:36:39 +01:00
|
|
|
public allOff(): void {
|
2017-06-10 22:32:56 +02:00
|
|
|
this.handlers = [];
|
2020-01-03 11:36:39 +01:00
|
|
|
this.singleHandlers = [];
|
2017-06-10 22:32:56 +02:00
|
|
|
}
|
2016-03-13 11:28:29 +01:00
|
|
|
|
2020-01-03 11:36:39 +01:00
|
|
|
public trigger(data?: T): void {
|
2017-06-10 22:32:56 +02:00
|
|
|
if (this.handlers) {
|
2022-04-04 19:37:31 +02:00
|
|
|
this.handlers.slice(0).forEach((h) => h(data));
|
2016-03-13 11:28:29 +01:00
|
|
|
}
|
2020-01-03 11:36:39 +01:00
|
|
|
if (this.singleHandlers) {
|
2022-04-04 19:37:31 +02:00
|
|
|
this.singleHandlers.slice(0).forEach((h) => h(data));
|
2020-01-03 11:36:39 +01:00
|
|
|
this.singleHandlers = [];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public hasListener(): boolean {
|
|
|
|
return this.handlers.length !== 0 || this.singleHandlers.length !== 0;
|
2017-06-10 22:32:56 +02:00
|
|
|
}
|
2016-03-13 11:28:29 +01:00
|
|
|
}
|
|
|
|
|
2020-01-03 11:36:39 +01:00
|
|
|
|
|
|
|
|