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