-
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathuseNotifyWatch.ts
More file actions
62 lines (50 loc) · 1.49 KB
/
useNotifyWatch.ts
File metadata and controls
62 lines (50 loc) · 1.49 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { matchNamePath } from '../utils/valueUtil';
import type { InternalNamePath, WatchCallBack } from '../interface';
import type { FormStore } from './useForm';
/**
* Call action with delay in macro task.
*/
export const macroTask = (fn: VoidFunction) => {
const channel = new MessageChannel();
channel.port1.onmessage = fn;
channel.port2.postMessage(null);
};
export default class WatcherCenter {
namePathList: InternalNamePath[] = [];
taskId: number = 0;
watcherList = new Set<WatchCallBack>();
form: FormStore;
constructor(form: FormStore) {
this.form = form;
}
public register(callback: WatchCallBack): VoidFunction {
this.watcherList.add(callback);
return () => {
this.watcherList.delete(callback);
};
}
public notify(namePath: InternalNamePath[]) {
// Insert with deduplication
namePath.forEach(path => {
if (this.namePathList.every(exist => !matchNamePath(exist, path))) {
this.namePathList.push(path);
}
});
this.doBatch();
}
private doBatch() {
this.taskId += 1;
const currentId = this.taskId;
macroTask(() => {
if (currentId === this.taskId && this.watcherList.size) {
const formInst = this.form.getForm();
const values = formInst.getFieldsValue();
const allValues = formInst.getFieldsValue(true);
this.watcherList.forEach(callback => {
callback(values, allValues, this.namePathList);
});
this.namePathList = [];
}
});
}
}