Scope.ts
54 lines
| 1.4 KiB
| video/mp2t
|
TypeScriptLexer
cin
|
r94 | import { IDestroyable, IRemovable } from "@implab/core-amd/interfaces"; | |
import { isDestroyable, isRemovable } from "@implab/core-amd/safe"; | |||
cin
|
r118 | import { isUnsubscribable, Unsubscribable } from "../observable"; | |
cin
|
r94 | ||
export interface IScope { | |||
cin
|
r102 | own(target: (() => void) | IDestroyable | IRemovable | Unsubscribable): void; | |
cin
|
r94 | } | |
cin
|
r131 | const guard = (cb: () => void) => { | |
try { | |||
cb(); | |||
} catch { | |||
// guard | |||
} | |||
}; | |||
cin
|
r94 | export class Scope implements IDestroyable, IScope { | |
cin
|
r131 | private readonly _pending: (() => void)[] = []; | |
private _disposed = false; | |||
cin
|
r94 | ||
static readonly dummy: IScope = { own() { } }; | |||
cin
|
r102 | own(target: (() => void) | IDestroyable | IRemovable | Unsubscribable) { | |
cin
|
r94 | if (target instanceof Function) { | |
cin
|
r131 | this._own(target); | |
cin
|
r94 | } else if (isDestroyable(target)) { | |
cin
|
r131 | this._own(() => target.destroy()); | |
cin
|
r94 | } else if (isRemovable(target)) { | |
cin
|
r131 | this._own(() => target.remove()); | |
cin
|
r118 | } else if (isUnsubscribable(target)) { | |
cin
|
r131 | this._own(() => target.unsubscribe()); | |
cin
|
r94 | } | |
} | |||
cin
|
r131 | private _own(target: () => void) { | |
if (this._disposed) | |||
guard(target); | |||
else | |||
this._pending.push(target); | |||
} | |||
cin
|
r94 | clean() { | |
cin
|
r131 | this._pending.forEach(guard); | |
this._pending.length = 0; | |||
cin
|
r94 | } | |
destroy() { | |||
cin
|
r131 | if (!this._disposed) { | |
this._disposed = true; | |||
this.clean(); | |||
} | |||
cin
|
r94 | } | |
} |