1.1.1 โข Published 8 months ago
@asaidimu/events v1.1.1
@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
- Clean up subscriptions: Always call the unsubscribe function when you're done with a subscription.
- Batch processing: Enable async mode for high-frequency events to prevent blocking.
- Error handling: Provide a custom error handler for production environments.
- Monitor performance: Use
getMetrics()
to track event bus performance. - 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 processingbatchSize
: Number (default:1000
) - Maximum batch size for async processingbatchDelay
: Number (default:16
) - Delay between batch processing in mserrorHandler
: Function - Custom error handler for event processing errorscrossTab
: Boolean (default:false
) - Enable cross-tab notifications usingBroadcastChannel
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 eventsemit<TEventName>(event)
: Emit an eventgetMetrics()
: Get performance metricsclear()
: Clear all subscriptions, metrics, and cross-tab resources
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.