A TypeScript package for managing events using eventemitter3, providing a simple and efficient way to publish, subscribe, and unsubscribe from events.
npm install @enegix/eventssh
pnpm install @enegix/events
or
npm install @enegix/events
or
yarn add @enegix/events
`
Usage
$3
By default, using publish and subscribe without topics means the events are handled in the global topic.
`typescript
import { publish, subscribe, unsubscribeAll } from '@enegix/events';
// Subscribe to an event from anywhere in the application
subscribe('event1', (data) => {
console.log('Received data:', data);
});
// Publish an event
publish('event1', { message: 'Hello World!' });
`
$3
Creating a Topic encapsulates events to that specific topic, ensuring that events do not interfere with other topics.
`typescript
import { Topic } from '@enegix/events';
interface UserInfo {
id: string;
name: string;
email: string;
}
interface UserTopic {
CREATED: UserInfo;
DELETED: Pick;
UPDATE: 'SUCCESS' | 'FAILED';
}
const userTopic = new Topic();
// Subscribe to an event in this topic
userTopic.subscribe('CREATED', (data) => {
console.log('User created:', data.name); // data is of type UserInfo
});
// Publish an event in this topic
userTopic.publish('CREATED', { id: '1', name: 'John', email: 'john@example.com' }); // Typed
// Unsubscribe from all events in this topic
userTopic.unsubscribeAll();
``