1 |
const callbacks = new WeakMap();
|
2✔ |
2 |
const queue = new Set();
|
2✔ |
3 |
|
|
4 |
function execute() { |
|
5 |
try {
|
103✔ |
6 |
queue.forEach(target => { |
103✔ |
7 |
try {
|
214✔ |
8 |
callbacks.get(target)(); |
214✔ |
9 |
queue.delete(target);
|
212✔ |
10 |
} catch (e) {
|
|
11 |
queue.delete(target);
|
2✔ |
12 |
throw e;
|
2✔ |
13 |
} |
|
14 |
}); |
|
15 |
} catch (e) {
|
|
16 |
if (queue.size) execute();
|
|
17 |
throw e;
|
2✔ |
18 |
} |
|
19 |
} |
|
20 |
|
|
21 |
export function dispatch(target) { |
|
22 |
if (callbacks.has(target)) {
|
|
23 |
if (!queue.size) {
|
|
24 |
requestAnimationFrame(execute); |
102✔ |
25 |
} |
|
26 |
queue.add(target); |
305✔ |
27 |
} |
|
28 |
} |
|
29 |
|
|
30 |
export function subscribe(target, cb) { |
|
31 |
callbacks.set(target, cb); |
221✔ |
32 |
dispatch(target); |
221✔ |
33 |
|
|
34 |
return function unsubscribe() { |
221✔ |
35 |
queue.delete(target);
|
208✔ |
36 |
callbacks.delete(target);
|
208✔ |
37 |
}; |
|
38 |
} |