Skip to content

TypeScript-based package for type-safe event publishing and subscribing, encapsulating events within specific topics to prevent interference. It offers a straightforward API for integrating event handling into applications.

License

Notifications You must be signed in to change notification settings

enegixinc/events

Repository files navigation

Events Package

Overview

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.

Features

  • Encapsulate events in topics
  • Type-safe events with TypeScript

Installation

To install the package, use npm or yarn:

pnpm install @enegix/events
# or
npm install @enegix/events
# or
yarn add @enegix/events

Usage

Basic Usage

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!' });

Using Topic Class for Encapsulated Typed Events

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();

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.

About

TypeScript-based package for type-safe event publishing and subscribing, encapsulating events within specific topics to prevent interference. It offers a straightforward API for integrating event handling into applications.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published