/
Global.ts
77 lines (66 loc) · 1.76 KB
/
Global.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { supportFinalizer } from './util'
/** @public */
export class Global<T extends object> {
private _ref: T | WeakRef<T> | null
private _param: any
private _callback: ((param: any) => void) | undefined
private static readonly _registry = supportFinalizer
? new FinalizationRegistry((value: Global<any>) => {
value._ref = null
if (typeof value._callback === 'function') {
value._callback(value._param)
}
})
: undefined!
constructor (value: T) {
this._ref = value
}
setWeak<P> (param: any, callback: (param: P) => void): void {
if (this._ref === null) return
if (!supportFinalizer) return
if (this._ref instanceof WeakRef) return
this._param = param
this._callback = callback
Global._registry.register(this._ref, this, this)
this._ref = new WeakRef<T>(this._ref)
}
clearWeak (): void {
if (this._ref === null) return
if (!supportFinalizer) return
if (this._ref instanceof WeakRef) {
try {
Global._registry.unregister(this)
} catch (_) {}
this._param = undefined
this._callback = undefined
this._ref = this._ref.deref() as T
}
}
reset (other?: T | WeakRef<T>): void {
if (supportFinalizer) {
try {
Global._registry.unregister(this)
} catch (_) {}
}
this._param = undefined
this._callback = undefined
if (other) {
this._ref = other
} else {
this._ref = null
}
}
isEmpty (): boolean {
return this._ref === null
}
deref (): T | undefined {
if (!supportFinalizer) {
return (this._ref as T | null) ?? undefined
}
if (this._ref === null) return undefined
if (this._ref instanceof WeakRef) {
return this._ref.deref()
}
return this._ref
}
}