@therms/react-event-bus
v1.0.2
Published
An event-bus for use in React applications
Downloads
162
Readme
@therms/react-event-bus
An event-bus for use in React applications. This library provides a simple, type-safe way to handle cross-component communication using an event bus pattern.
Installation
npm install @therms/react-event-busUsage
1. Create an Event Notifier
Create an instance of the event notifier. You can define the payload type for type safety.
// events.ts
import { makeEventNotifier } from '@therms/react-event-bus';
// Define the payload type
type UserLoggedInPayload = {
userId: string;
timestamp: number;
};
export const userLoginEvent = makeEventNotifier<UserLoggedInPayload>('USER_LOGIN');2. Publish Events
Trigger an event from anywhere in your application.
import { userLoginEvent } from './events';
userLoginEvent.notify({
userId: '12345',
timestamp: Date.now(),
});3. Subscribe to Events (React Hook)
Use the useEventListener hook within your React components to listen for events. The hook automatically handles cleanup when the component unmounts.
import React from 'react';
import { userLoginEvent } from './events';
const UserStatus = () => {
userLoginEvent.useEventListener((payload) => {
console.log('User logged in:', payload.userId);
}, []); // Dependency array, similar to useEffect
return <div>Waiting for login...</div>;
};4. Subscribe to Events (Vanilla JS/TS)
You can also subscribe outside of React components using the listen method.
import { userLoginEvent } from './events';
const unsubscribe = userLoginEvent.listen((payload) => {
console.log('Received event:', payload);
});
// Later, to stop listening:
unsubscribe();API
makeEventNotifier<Payload>(name: string)
Creates a new event notifier instance.
name: A unique name for the event (mainly for debugging purposes).Payload: The type of data that will be passed with the event.
Returns an object with the following methods:
notify(payload: Payload): Triggers the event with the given payload.useEventListener(listener: (payload: Payload) => void, deps: any[]): A React hook to subscribe to the event.listen(listener: (payload: Payload) => void): Subscribes to the event. Returns an unsubscribe function.name: The name of the event.
Example Use Case: Centralized App Events
Here's a practical example of organizing events in a centralized object for a map-based application:
// events/AppEvents.ts
import { makeEventNotifier } from '@therms/react-event-bus';
type LatLng = { lat: number; lng: number };
export const AppEvents = {
// Content Panel events
SET_CONTENT_EVENT: makeEventNotifier<{ eventId: string; source: string }>(
'SET_CONTENT_EVENT',
),
SET_CONTENT_LOCATION: makeEventNotifier<{ locationId: string; source: string }>(
'SET_CONTENT_LOCATION',
),
SET_CONTENT_USER: makeEventNotifier<{ userId: string; source: string }>(
'SET_CONTENT_USER',
),
// Map events
SET_MAP_CENTER: makeEventNotifier<{ coords: LatLng; zoom?: number; source: string }>(
'SET_MAP_CENTER',
),
SET_MAP_BOUNDS: makeEventNotifier<{ bounds: { ne: LatLng; sw: LatLng }; source: string }>(
'SET_MAP_BOUNDS',
),
};// components/Map.tsx
import { AppEvents } from '../events/AppEvents';
export const Map = () => {
AppEvents.SET_MAP_CENTER.useEventListener(({ coords, zoom }) => {
map.flyTo(coords, zoom);
}, []);
AppEvents.SET_MAP_BOUNDS.useEventListener(({ bounds }) => {
map.fitBounds([bounds.sw, bounds.ne]);
}, []);
return <div id="map" />;
};// components/LocationCard.tsx
import { AppEvents } from '../events/AppEvents';
export const LocationCard = ({ location }) => {
const handleClick = () => {
AppEvents.SET_MAP_CENTER.notify({
coords: location.coords,
zoom: 15,
source: 'LocationCard',
});
AppEvents.SET_CONTENT_LOCATION.notify({
locationId: location.id,
source: 'LocationCard',
});
};
return <div onClick={handleClick}>{location.name}</div>;
};License
MIT
