use-app-events
v1.7.9
Published
Create, trigger and listen for custom events in vanilla JavaScript and React.
Downloads
65
Maintainers
Readme
use-app-events
Create, trigger and listen for custom events in vanilla JavaScript and React.
📦 Small package (~19 kB)
🍃 Tree-shakeable
📝 Well documented
🛡️ Strictly typed with TypeScript
♻️ Events interact with each other across different browser tabs
⚛️ Exports a convenient hook for React developers
Examples
import { notifyEventListeners, listenForEvents } from 'use-app-events';
// 1. Listen for an event
listenForEvents('media-resume', () => {
// do something when the event is emitted
});
// 2. Emit an event
notifyEventListeners('media-resume');
// 3. Listen for an event (it will only be processed once here)
listenForEvents.once('load-resource', async (url) => {
await fetch(url);
});
// 4. Emit an event with some data
notifyEventListeners(
'load-resource',
'https://www.npmjs.com/package/use-app-events'
);
// 5. Listen for multiple events
const unlisten = listenForEvents(['event-1', 'event-2'], (eventType, url) => {
if (eventType === 'event-1') {
// do something when 'event-1' is emitted
}
if (eventType === 'event-2') {
// do something when 'event-2' is emitted
}
});
// 6. Stop listening for events
unlisten();
// 7. Emit multiple events with some data
notifyEventListeners(
['event-1', 'event-2'],
'https://www.npmjs.com/package/use-app-events'
);Install
npm
npm install use-app-eventspnpm
pnpm add use-app-eventsExports
- notifyEventListeners
- Function to notify all listeners of the specified event type(s) subscribed via
listenForEvents.
- Function to notify all listeners of the specified event type(s) subscribed via
- listenForEvents
- Function to subscribe and listen for the specified event type(s) to occur in the app.
- listenForEvents.once
- Function to subscribe and listen for the specified event type(s) to occur in the app once.
- useAppEvents
- Hook for managing application events in React.
- heap
- (readonly) Collection of resources operated by the package.
- options
- Collection of options used to adjust the behavior of the package.
This is a truncated version of README to reduce the package size.
[See full docs on GitHub]
License
Author
Maksym Marchuk
