1 | import * as React from 'react';
|
2 | export function createMessageBus() {
|
3 | const listeners = new Map();
|
4 | function subscribe(topic, callback) {
|
5 | let topicListeners = listeners.get(topic);
|
6 | if (!topicListeners) {
|
7 | topicListeners = new Set([callback]);
|
8 | listeners.set(topic, topicListeners);
|
9 | } else {
|
10 | topicListeners.add(callback);
|
11 | }
|
12 | return () => {
|
13 | topicListeners.delete(callback);
|
14 | if (topicListeners.size === 0) {
|
15 | listeners.delete(topic);
|
16 | }
|
17 | };
|
18 | }
|
19 | function publish(topic, ...args) {
|
20 | const topicListeners = listeners.get(topic);
|
21 | if (topicListeners) {
|
22 | topicListeners.forEach(callback => callback(...args));
|
23 | }
|
24 | }
|
25 | return {
|
26 | subscribe,
|
27 | publish
|
28 | };
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | export default function useMessageBus() {
|
35 | const bus = React.useRef();
|
36 | if (!bus.current) {
|
37 | bus.current = createMessageBus();
|
38 | }
|
39 | return bus.current;
|
40 | } |
\ | No newline at end of file |