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