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