1.1.1 โ€ข Published 8 months ago

@asaidimu/events v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

@asaidimu/events

A lightweight, type-safe event bus implementation for TypeScript applications with zero dependencies.

Features

  • ๐ŸŽฏ Fully type-safe event definitions and payloads
  • โšก High-performance event emission and subscription
  • ๐ŸŽฎ Async and batched event processing support
  • ๐Ÿ“Š Built-in performance monitoring
  • ๐Ÿงน Automatic memory management
  • ๐ŸŒ Cross-tab notifications via BroadcastChannel
  • 0๏ธโƒฃ Zero dependencies

Installation

npm install @asaidimu/events

Usage

Basic Usage

import { createEventBus } from '@asaidimu/events';

// Define your event types
interface AppEvents {
  'user:created': {
    id: string;
    name: string;
  };
  'user:deleted': {
    id: string;
  };
}

// Create a type-safe event bus
const bus = createEventBus<AppEvents>();

// Subscribe to events
const unsubscribe = bus.subscribe('user:created', user => {
  console.log(`New user: ${user.name}`);
});

// Emit events
bus.emit({
  name: 'user:created',
  payload: {
    id: '1',
    name: 'John'
  }
});

// Cleanup
unsubscribe();

Advanced Configuration

const bus = createEventBus<AppEvents>({
  async: true,              // Enable async event processing
  batchSize: 1000,         // Process events in batches
  batchDelay: 16,          // Batch processing delay in ms
  errorHandler: (error) => { // Custom error handling
    console.error('Event error:', error);
  },
  crossTab: true,          // Enable cross-tab notifications (default: true)
  channelName: 'my-app-events' // Custom channel name for cross-tab communication
});

Cross-Tab Notifications

Events emitted in one browser tab are automatically broadcasted to other tabs with the same event bus configuration.

// In Tab 1
const bus = createEventBus<AppEvents>({ crossTab: true });
bus.subscribe('user:created', user => {
  console.log(`Tab 1: New user - ${user.name}`);
});

// In Tab 2
const bus2 = createEventBus<AppEvents>({ crossTab: true });
bus2.subscribe('user:created', user => {
  console.log(`Tab 2: New user - ${user.name}`);
});

// In Tab 1: Emit an event
bus.emit({
  name: 'user:created',
  payload: { id: '1', name: 'John' }
});

// Output:
// Tab 1: New user - John
// Tab 2: New user - John

Performance Monitoring

// Get performance metrics
const metrics = bus.getMetrics();
console.log(metrics.totalEvents);         // Total events processed
console.log(metrics.activeSubscriptions); // Current active subscriptions
console.log(metrics.eventCounts);         // Events per type
console.log(metrics.averageEmitDuration); // Average processing time

Memory Management

class Component {
  private unsubscribes: Array<() => void> = [];
  
  init() {
    // Store unsubscribe functions
    this.unsubscribes.push(
      bus.subscribe('user:created', this.handleUser)
    );
  }
  
  destroy() {
    // Clean up all subscriptions
    this.unsubscribes.forEach(unsub => unsub());
    this.unsubscribes = [];
  }
}

Performance Tips

  1. Clean up subscriptions: Always call the unsubscribe function when you're done with a subscription.
  2. Batch processing: Enable async mode for high-frequency events to prevent blocking.
  3. Error handling: Provide a custom error handler for production environments.
  4. Monitor performance: Use getMetrics() to track event bus performance.
  5. Cross-tab uniqueness: Use a unique channelName if multiple event buses coexist in your app.

API Reference

createEventBus<TEventMap>(options?)

Creates a new event bus with the specified event map type.

Options

  • async: Boolean (default: false) - Enable async event processing
  • batchSize: Number (default: 1000) - Maximum batch size for async processing
  • batchDelay: Number (default: 16) - Delay between batch processing in ms
  • errorHandler: Function - Custom error handler for event processing errors
  • crossTab: Boolean (default: false) - Enable cross-tab notifications using BroadcastChannel
  • channelName: String (default: 'event-bus-channel') - Unique channel name for cross-tab communication

Returns

An EventBus instance with the following methods:

  • subscribe<TEventName>(eventName, callback): Subscribe to events
  • emit<TEventName>(event): Emit an event
  • getMetrics(): Get performance metrics
  • clear(): Clear all subscriptions, metrics, and cross-tab resources

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.