cxPubSub
Auto-generated documentation from JSDoc comments
cxPubSub¶
Global Publish/Subscribe messaging bus for real-time event-driven communication. Enables decoupled components to communicate through named channels with event IDs.
Example¶
import { subscribe, publish } from 'cxPubSub';
export async function main() {
try {
// Subscribe to an event channel
await subscribe('myEvent', '1234', (data) => {
console.log('Received data:', JSON.stringify(data));
});
// Allow time for subscription to be established
await new Promise(resolve => setTimeout(resolve, 500));
// Publish an event to the channel
await publish('myEvent', '1234', { my: 'data' });
// Allow time for the message to be received
await new Promise(resolve => setTimeout(resolve, 500));
return { message: 'Event published and subscriber notified.' };
} catch (err) {
console.error(err.message);
}
}
Kind: global class
- cxPubSub
- .publish(channel, id, data) ⇒
Promise.<void> - .subscribe(channel, id, callback) ⇒
Promise.<void>
- .publish(channel, id, data) ⇒
cxPubSub.publish(channel, id, data) ⇒ Promise.<void>¶
Publish an event to a channel
Kind: static method of cxPubSub
| Param | Type | Description |
|---|---|---|
| channel | string |
The event channel name to publish to |
| id | string |
A unique event identifier (subscribers can filter by this ID or use '*' for all) |
| data | object |
The payload data to send to subscribers |
Example
// Publish a simple event
await publish('orderUpdates', 'order-123', { status: 'shipped' });
// Publish to notify all subscribers of a channel
await publish('notifications', 'user-456', {
type: 'alert',
message: 'New message received'
});
cxPubSub.subscribe(channel, id, callback) ⇒ Promise.<void>¶
Subscribe to events on a channel
Kind: static method of cxPubSub
| Param | Type | Description |
|---|---|---|
| channel | string |
The event channel name to subscribe to |
| id | string |
The event ID to listen for, or '*' to receive all events on the channel |
| callback | function |
Callback function invoked when an event is received |
| callback.data | object |
The event payload data |
Example
// Subscribe to a specific event ID
await subscribe('orderUpdates', 'order-123', (data) => {
console.log('Order update:', data);
});
// Subscribe to all events on a channel using wildcard
await subscribe('notifications', '*', (data) => {
console.log('Notification received:', data);
});