eventbus-js-fast
v2.0.1
Published
A powerful and flexible event bus system with middleware support, validation, scheduling, and scoped namespaces
Maintainers
Readme
EventBus
A powerful and flexible event bus system built with TypeScript, featuring middleware support, event validation, scheduling, and scoped namespaces.
Features
- 🚀 Event Subscription & Emission - Simple pub/sub pattern
- 🔧 Middleware Support - Process events before/after emission
- ✅ Event Validation - Validate event data before processing
- ⏰ Event Scheduling - Schedule events for future emission
- 🔄 Recurring Events - Set up interval-based event emission
- 🏷️ Scoped Namespaces - Organize events with namespaces
- 📊 Statistics & History - Track event usage and history
- 🐛 Debug Logging - Comprehensive logging for development
- 🎯 TypeScript Support - Full type safety and IntelliSense
Installation
npm i eventbus-js-fastQuick Start
import EventBus from 'eventbus-js-fast';
// Subscribe to events
EventBus.$on('user:login', (user) => {
console.log('User logged in:', user);
});
// Emit events
EventBus.$emit('user:login', { id: 1, name: 'John' });
// Use middleware
EventBus.$before('user:login', (data) => {
console.log('Before login:', data);
return data;
});
// Validate events
EventBus.$validate('user:login', (data) => {
return data && typeof data.id === 'number';
});Architecture
The EventBus is built with a clean, professional architecture:
src/
├── types.ts # Type definitions and interfaces
├── constants.ts # Configuration constants and enums
├── utils.ts # Utility functions and helpers
├── EventBus.ts # Main EventBus class implementation
├── factory.ts # Factory functions and instances
└── index.ts # Main entry point and exportsCore Components
types.ts- Contains all TypeScript interfaces and type definitionsconstants.ts- Configuration values, event types, and logging constantsutils.ts- Helper functions for common operationsEventBus.ts- Main class implementing the event bus functionalityfactory.ts- Factory functions for creating instancesindex.ts- Main entry point with all exports
API Reference
Core Methods
$on<T>(event: string, callback: EventCallback<T>)
Subscribe to an event.
EventBus.$on('user:created', (user: User) => {
console.log('New user:', user);
});$off<T>(event: string, callback: EventCallback<T>)
Unsubscribe from an event.
EventBus.$off('user:created', callback);$emit<T>(event: string, data: T): Promise<void>
Emit an event to all registered listeners.
await EventBus.$emit('user:created', { id: 1, name: 'John' });$once<T>(event: string, callback: EventCallback<T>)
Subscribe to an event once (automatically unsubscribes after first emission).
EventBus.$once('user:deleted', (user) => {
console.log('User deleted:', user);
});Advanced Features
Middleware
// Run before event emission
EventBus.$before('user:login', (data) => {
data.timestamp = Date.now();
return data;
});
// Run after event emission
EventBus.$after('user:login', (data) => {
console.log('User logged in at:', data.timestamp);
return data;
});Event Validation
EventBus.$validate('user:login', (data) => {
return data.email && data.password;
});Scheduled Events
// Schedule event for future emission
const id = EventBus.$schedule('reminder', { message: 'Meeting in 5 minutes' }, Date.now() + 300000);
// Cancel scheduled event
EventBus.$cancelScheduled(id);Recurring Events
// Emit event every 5 seconds
const id = EventBus.$interval('heartbeat', { status: 'alive' }, 5000);
// Cancel recurring event
EventBus.$cancelScheduled(id);Scoped Events
const userEvents = EventBus.$scope('user');
const systemEvents = EventBus.$scope('system');
userEvents.$on('profile:update', callback);
systemEvents.$on('maintenance:start', callback);Utility Methods
$stats(): EventStats
Get statistics about event usage.
const stats = EventBus.$stats();
console.log(`Total events: ${stats.totalEvents}`);
console.log(`Total listeners: ${stats.totalListeners}`);$history(event?: string, limit?: number): EventHistoryRecord[]
Get event history.
const history = EventBus.$history('user:login', 10);$debug(enabled: boolean): void
Enable or disable debug logging.
EventBus.$debug(true);$clear(): void
Clear all events, middleware, and scheduled events.
EventBus.$clear();Creating Multiple Instances
You can create multiple EventBus instances for different contexts:
import { createEventBus, EventBus } from 'eventbus-js-fast';
// Create a new instance
const userEventBus = createEventBus({ debug: true });
// Or use the class directly
const systemEventBus = new EventBus({ maxHistorySize: 500 });Configuration
import { createEventBus } from 'eventbus-js-fast';
const eventBus = createEventBus({
debug: true, // Enable debug logging
maxHistorySize: 2000 // Increase history size
});Error Handling
The EventBus includes built-in error handling:
// Middleware errors are caught and logged
EventBus.$before('user:action', (data) => {
throw new Error('Something went wrong');
// Error is caught and logged, event continues
});
// Validation errors prevent event emission
EventBus.$validate('user:action', (data) => {
if (!data.userId) {
return false; // Event won't be emitted
}
return true;
});Performance Considerations
- Events are processed synchronously by default
- Middleware and validation run in sequence
- History is automatically trimmed to prevent memory leaks
- Scheduled events are cleaned up automatically
Testing
npm testThe test suite covers all major functionality including edge cases and integration scenarios.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
License
MIT License - see LICENSE file for details.
Changelog
v2.0.1
- Build target downleveled to ES2018 to avoid nullish coalescing in dist
- Updated README install/imports to
eventbus-js-fast
v2.0.0
- Complete code restructuring for better maintainability
- Separated concerns into multiple files
- Added proper TypeScript interfaces
- Improved error handling and validation
- Enhanced documentation and examples
v1.0.0
- Initial release with basic event bus functionality
