@@ -1,43 +1,55 | |||
|
1 | 1 | import { IDestroyable, IRemovable } from "@implab/core-amd/interfaces"; |
|
2 | 2 | import { isDestroyable, isRemovable } from "@implab/core-amd/safe"; |
|
3 | 3 | import { isUnsubscribable, Unsubscribable } from "../observable"; |
|
4 | 4 | |
|
5 | 5 | export interface IScope { |
|
6 | 6 | own(target: (() => void) | IDestroyable | IRemovable | Unsubscribable): void; |
|
7 | 7 | } |
|
8 | 8 | |
|
9 | const guard = (cb: () => void) => { | |
|
10 | try { | |
|
11 | cb(); | |
|
12 | } catch { | |
|
13 | // guard | |
|
14 | } | |
|
15 | }; | |
|
16 | ||
|
9 | 17 | export class Scope implements IDestroyable, IScope { |
|
10 |
private readonly _ |
|
|
18 | private readonly _pending: (() => void)[] = []; | |
|
19 | ||
|
20 | private _disposed = false; | |
|
11 | 21 | |
|
12 | 22 | static readonly dummy: IScope = { own() { } }; |
|
13 | 23 | |
|
14 | 24 | own(target: (() => void) | IDestroyable | IRemovable | Unsubscribable) { |
|
15 | 25 | if (target instanceof Function) { |
|
16 |
this._ |
|
|
26 | this._own(target); | |
|
17 | 27 | } else if (isDestroyable(target)) { |
|
18 |
this._ |
|
|
28 | this._own(() => target.destroy()); | |
|
19 | 29 | } else if (isRemovable(target)) { |
|
20 |
this._ |
|
|
30 | this._own(() => target.remove()); | |
|
21 | 31 | } else if (isUnsubscribable(target)) { |
|
22 |
this._ |
|
|
32 | this._own(() => target.unsubscribe()); | |
|
23 | 33 | } |
|
24 | 34 | } |
|
25 | 35 | |
|
36 | private _own(target: () => void) { | |
|
37 | if (this._disposed) | |
|
38 | guard(target); | |
|
39 | else | |
|
40 | this._pending.push(target); | |
|
41 | } | |
|
42 | ||
|
26 | 43 | clean() { |
|
27 | const guard = (cb: () => void) => { | |
|
28 | try { | |
|
29 | cb(); | |
|
30 | } catch { | |
|
31 | // guard | |
|
32 | } | |
|
33 | }; | |
|
34 | ||
|
35 | this._cleanup.forEach(guard); | |
|
36 | this._cleanup.length = 0; | |
|
44 | this._pending.forEach(guard); | |
|
45 | this._pending.length = 0; | |
|
37 | 46 | } |
|
38 | 47 | |
|
39 | 48 | destroy() { |
|
40 | this.clean(); | |
|
49 | if (!this._disposed) { | |
|
50 | this._disposed = true; | |
|
51 | this.clean(); | |
|
52 | } | |
|
41 | 53 | } |
|
42 | 54 | |
|
43 | 55 | } No newline at end of file |
General Comments 0
You need to be logged in to leave comments.
Login now