-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
emitter.ts
50 lines (42 loc) · 1.09 KB
/
emitter.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
48
49
50
type Force = () => void;
interface EmitMap {
[fieldId: string]: Array<Force>;
}
const mapping: EmitMap = {};
export function on(fieldId: string | Array<string>, cb: Force) {
if (Array.isArray(fieldId)) {
const disposers: Array<Force> = [];
fieldId.forEach((f) => {
if (!mapping[f]) { mapping[f] = []; }
mapping[f].push(cb);
disposers.push(() => {
if (mapping[f].indexOf(cb) !== -1) {
mapping[f].splice(mapping[f].indexOf(cb), 1);
}
});
});
return () => { disposers.forEach((c) => { c(); }); };
}
if (!mapping[fieldId]) {
mapping[fieldId] = [];
}
mapping[fieldId].push(cb);
return () => {
if (mapping[fieldId].indexOf(cb) !== -1) {
mapping[fieldId].splice(mapping[fieldId].indexOf(cb), 1);
}
};
}
export function emit(fieldId: string | Array<string>) {
if (Array.isArray(fieldId)) {
fieldId.forEach((f) => { notify(`${f}`); });
} else {
notify(`${fieldId}`);
}
notify('all');
}
function notify(fieldId: string) {
if (mapping[fieldId]) {
mapping[fieldId].forEach((cb) => { cb(); });
}
}