1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2025-01-14 14:43:17 +08:00

54 lines
1.3 KiB
TypeScript
Raw Normal View History

2016-03-13 11:28:29 +01:00
export class Event<T> {
protected handlers: ((data?: T) => void)[] = [];
protected singleHandlers: ((data?: T) => void)[] = [];
2016-03-13 11:28:29 +01:00
public on(handler: (data?: T) => void): void {
2022-04-04 19:37:31 +02:00
if (typeof handler !== 'function') {
throw new Error('Event::on: Handler is not a function');
2016-03-13 11:28:29 +01:00
}
this.handlers.push(handler);
}
2016-03-13 11:28:29 +01:00
public once(handler: (data?: T) => void): void {
2022-04-04 19:37:31 +02:00
if (typeof handler !== 'function') {
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);
}
2016-03-13 11:28:29 +01:00
public allOff(): void {
this.handlers = [];
this.singleHandlers = [];
}
2016-03-13 11:28:29 +01:00
public trigger(data?: T): void {
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
}
if (this.singleHandlers) {
2022-04-04 19:37:31 +02:00
this.singleHandlers.slice(0).forEach((h) => h(data));
this.singleHandlers = [];
}
}
public hasListener(): boolean {
return this.handlers.length !== 0 || this.singleHandlers.length !== 0;
}
2016-03-13 11:28:29 +01:00
}