-
Notifications
You must be signed in to change notification settings - Fork 215
/
Event.ts
41 lines (33 loc) · 1.15 KB
/
Event.ts
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
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
import { Logger } from "./Logger";
/**
* @internal
*/
export type Callback<EventType extends unknown[]> = (...ev: EventType) => (Promise<void> | void);
/**
* @internal
*/
export class Event<EventType extends unknown[]> {
protected readonly _logger: Logger;
private readonly _callbacks: Array<Callback<EventType>> = [];
public constructor(protected readonly _name: string) {
this._logger = new Logger(`Event('${this._name}')`);
}
public addHandler(cb: Callback<EventType>): () => void {
this._callbacks.push(cb);
return () => this.removeHandler(cb);
}
public removeHandler(cb: Callback<EventType>): void {
const idx = this._callbacks.lastIndexOf(cb);
if (idx >= 0) {
this._callbacks.splice(idx, 1);
}
}
public async raise(...ev: EventType): Promise<void> {
this._logger.debug("raise:", ...ev);
for (const cb of this._callbacks) {
await cb(...ev);
}
}
}