You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
937 B
JavaScript
42 lines
937 B
JavaScript
'use client';
|
|
|
|
import * as React from 'react';
|
|
export function createMessageBus() {
|
|
const listeners = new Map();
|
|
function subscribe(topic, callback) {
|
|
let topicListeners = listeners.get(topic);
|
|
if (!topicListeners) {
|
|
topicListeners = new Set([callback]);
|
|
listeners.set(topic, topicListeners);
|
|
} else {
|
|
topicListeners.add(callback);
|
|
}
|
|
return () => {
|
|
topicListeners.delete(callback);
|
|
if (topicListeners.size === 0) {
|
|
listeners.delete(topic);
|
|
}
|
|
};
|
|
}
|
|
function publish(topic, ...args) {
|
|
const topicListeners = listeners.get(topic);
|
|
if (topicListeners) {
|
|
topicListeners.forEach(callback => callback(...args));
|
|
}
|
|
}
|
|
return {
|
|
subscribe,
|
|
publish
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @ignore - internal hook.
|
|
*/
|
|
export function useMessageBus() {
|
|
const bus = React.useRef();
|
|
if (!bus.current) {
|
|
bus.current = createMessageBus();
|
|
}
|
|
return bus.current;
|
|
} |