@@ -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 | export class Scope implements IDestroyable, IScope { | |
|
10 | private readonly _cleanup: (() => void)[] = []; | |
|
11 | ||
|
12 | static readonly dummy: IScope = { own() { } }; | |
|
13 | ||
|
14 | own(target: (() => void) | IDestroyable | IRemovable | Unsubscribable) { | |
|
15 | if (target instanceof Function) { | |
|
16 | this._cleanup.push(target); | |
|
17 | } else if (isDestroyable(target)) { | |
|
18 | this._cleanup.push(() => target.destroy()); | |
|
19 | } else if (isRemovable(target)) { | |
|
20 | this._cleanup.push(() => target.remove()); | |
|
21 | } else if (isUnsubscribable(target)) { | |
|
22 | this._cleanup.push(() => target.unsubscribe()); | |
|
23 | } | |
|
24 | } | |
|
25 | ||
|
26 | clean() { | |
|
27 | 9 |
|
|
28 | 10 |
|
|
29 | 11 |
|
|
30 | 12 |
|
|
31 | 13 |
|
|
32 | 14 | } |
|
33 | 15 | }; |
|
34 | 16 | |
|
35 | this._cleanup.forEach(guard); | |
|
36 | this._cleanup.length = 0; | |
|
17 | export class Scope implements IDestroyable, IScope { | |
|
18 | private readonly _pending: (() => void)[] = []; | |
|
19 | ||
|
20 | private _disposed = false; | |
|
21 | ||
|
22 | static readonly dummy: IScope = { own() { } }; | |
|
23 | ||
|
24 | own(target: (() => void) | IDestroyable | IRemovable | Unsubscribable) { | |
|
25 | if (target instanceof Function) { | |
|
26 | this._own(target); | |
|
27 | } else if (isDestroyable(target)) { | |
|
28 | this._own(() => target.destroy()); | |
|
29 | } else if (isRemovable(target)) { | |
|
30 | this._own(() => target.remove()); | |
|
31 | } else if (isUnsubscribable(target)) { | |
|
32 | this._own(() => target.unsubscribe()); | |
|
33 | } | |
|
34 | } | |
|
35 | ||
|
36 | private _own(target: () => void) { | |
|
37 | if (this._disposed) | |
|
38 | guard(target); | |
|
39 | else | |
|
40 | this._pending.push(target); | |
|
41 | } | |
|
42 | ||
|
43 | clean() { | |
|
44 | this._pending.forEach(guard); | |
|
45 | this._pending.length = 0; | |
|
37 | 46 | } |
|
38 | 47 | |
|
39 | 48 | destroy() { |
|
49 | if (!this._disposed) { | |
|
50 | this._disposed = true; | |
|
40 | 51 | this.clean(); |
|
41 | 52 | } |
|
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