forked from tylerlong/manate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact.ts
47 lines (41 loc) · 1.27 KB
/
react.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
39
40
41
42
43
44
45
46
47
// eslint-disable-next-line node/no-unpublished-import
import React from 'react';
import {useProxy, run, releaseChildren, ProxyType} from '.';
import {ProxyEvent} from './models';
export class Component<P = {}, S = {}> extends React.Component<P, S> {
propsProxy?: ProxyType<P>;
isTrigger!: (event: ProxyEvent) => boolean;
listener = (event: ProxyEvent) => {
if (this.isTrigger(event)) {
this.forceUpdate();
}
};
dispose() {
if (this.propsProxy) {
releaseChildren(this.propsProxy);
this.propsProxy.__emitter__.off('event', this.listener);
this.propsProxy = undefined;
}
}
constructor(props: Readonly<P>) {
super(props);
// rewrite render()
const render = this.render.bind(this);
this.render = () => {
this.dispose();
this.propsProxy = useProxy(this.props);
const [result, isTrigger] = run(this.propsProxy, render);
this.isTrigger = isTrigger;
this.propsProxy.__emitter__.on('event', this.listener);
return result;
};
// rewrite componentWillUnmount()
const componentWillUnmount = this.componentWillUnmount
? this.componentWillUnmount.bind(this)
: () => {};
this.componentWillUnmount = () => {
this.dispose();
componentWillUnmount();
};
}
}