The Events package provides a simple and type-safe way to publish and subscribe to events in your application. It allows you to encapsulate events in topics, ensuring that events do not interfere with other topics.
- Encapsulate events in topics
- Type-safe events with TypeScript
To install the package, use npm or yarn:
pnpm install @enegix/events
# or
npm install @enegix/events
# or
yarn add @enegix/events
By default, using publish and subscribe without topics means the events are handled in the global topic.
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!' });
Creating a Topic
encapsulates events to that specific topic, ensuring that events do not interfere with other topics.
import { Topic } from '@enegix/events';
interface UserInfo {
id: string;
name: string;
email: string;
}
interface UserTopic {
CREATED: UserInfo;
DELETED: Pick<UserInfo, 'id'>;
UPDATE: 'SUCCESS' | 'FAILED';
}
const userTopic = new Topic<UserTopic>();
// 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: '[email protected]' }); // Typed
// Unsubscribe from all events in this topic
userTopic.unsubscribeAll();
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License.