-
Notifications
You must be signed in to change notification settings - Fork 0
/
on.ts
42 lines (33 loc) · 895 Bytes
/
on.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
const callbacks = {};
if (
typeof window !== 'undefined' &&
typeof window.OnPropsMessageReceive === 'undefined'
) {
window.OnPropsMessageReceive = (message: string) => {
try {
const { key, payload } = JSON.parse(message);
if (typeof callbacks[key] === 'undefined') return;
callbacks[key].forEach(cb => {
if (typeof cb !== 'function') return;
cb(payload);
});
} catch (error) {
console.error('OnPropsMessageReceive is invalid', error.message);
}
};
}
export const off = (key: string, cb: any) => {
if (typeof callbacks[key] === 'undefined') {
return;
}
const index = callbacks[key].indexOf(cb);
if (index !== -1) {
delete callbacks[key][index];
}
};
export default function(key: string, cb: any) {
if (typeof callbacks[key] === 'undefined') {
callbacks[key] = [];
}
callbacks[key].push(cb);
}