-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto-dispose.ts
38 lines (33 loc) · 1021 Bytes
/
auto-dispose.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import * as React from "react";
const DISPOSER_SYMBOL = Symbol("disposerList");
export interface IReactClass extends React.Component<any> {
componentWillUnmount?: () => void,
readonly [DISPOSER_SYMBOL]?: Array<() => any>,
}
export function autoDispose(target: IReactClass, _: string, descriptor: PropertyDescriptor):
PropertyDescriptor {
const original = descriptor.value;
const oldUnmount = target.componentWillUnmount;
if (!target[DISPOSER_SYMBOL]) {
Object.defineProperty(target, DISPOSER_SYMBOL, {
value: [],
});
}
descriptor.value = function(...args: any[]): void {
const disposer = original.apply(this, args);
if (target[DISPOSER_SYMBOL]) {
target[DISPOSER_SYMBOL]!.push(disposer);
}
};
Object.defineProperty(target, "componentWillUnmount", {
value(): void {
oldUnmount && oldUnmount();
if (target[DISPOSER_SYMBOL] !== undefined) {
target[DISPOSER_SYMBOL]!.forEach(f => f());
target[DISPOSER_SYMBOL]!.length = 0;
}
},
writable: true,
});
return descriptor;
}