/
LazyStatefulEvt.ts
54 lines (35 loc) 路 1.31 KB
/
LazyStatefulEvt.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
42
43
44
45
46
47
48
49
50
51
52
53
54
import { overwriteReadonlyProp } from "https://deno.land/x/tsafe@v1.6.4/lab/overwriteReadonlyProp.ts";
import { importProxy } from "./importProxy.ts";
import type { StatefulEvt } from "./types/index.ts"
export class LazyStatefulEvt<T> {
private initialPostCount = 0;
private initialState: T;
get evt(): StatefulEvt<T> {
if (this.__evt === undefined) {
this.__evt = new importProxy.StatefulEvt(this.initialState);
//NOTE: For avoid keeping strong reference
this.initialState = null as any;
overwriteReadonlyProp(this.__evt, "postCount", this.initialPostCount);
}
return this.__evt;
}
declare private __evt: StatefulEvt<T>;
constructor(initialState: T) {
this.initialState = initialState;
}
private __post(data: T, doWait: false): number;
private __post(data: T, doWait: true): Promise<void>;
private __post(data: T, doWait: boolean): number | Promise<void> {
if (this.__evt === undefined) {
this.initialState = data;
return ++this.initialPostCount;
}
return this.__evt[doWait ? "postAndWait" : "post"](data);
}
post(data: T) {
return this.__post(data, false);
}
postAndWait(data: T) {
return this.__post(data, true);
}
}