Create a Vue plugin for a typed event bus without using mitt. Use TypeScript mapped types so the $emit function autocompletes the payload type based on event name. Add a replay feature where new subscribers can request the last N events of a specific topic.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The EventBus stores listeners in a Map and maintains event history for replay. When emitting, it triggers all registered handlers and records the payload. The getHistory method retrieves stored events, optionally limiting results to the last N entries.
The replay method executes handlers against historical events, while replayAndSubscribe combines replay with a new subscription. Clearing functionality removes listeners and history either for specific events or globally, with clearHistory also supporting size-based trimming to maintain bounded storage.
For Vue integration, the plugin exposes the EventBus instance as a global property $eventBus on all components, making it accessible throughout the application without manual injection.
The interface defines the core contract for the event bus with full type safety. It supports standard pub/sub operations like on, once, and off for subscribing and unsubscribing from events. Beyond basic event handling, it includes history tracking via getHistory and replay capabilities through replay and replayAndSubscribe methods. The emit method broadcasts events with their payloads, while clear and clearHistory provide cleanup functionality for managing stored event data.
TypeScript Event Bus Plugin for Vue 3
I'll create a fully typed event bus with replay functionality, autocomplete support, and comprehensive examples.
✅ Full TypeScript Support - Autocomplete for event names and payloads
✅ No External Dependencies - Pure TypeScript/Vue implementation
✅ Replay Functionality - Get last N events for new subscribers
✅ History Management - Configurable max history size
✅ Async Support - Handlers can be async
✅ Vue 3 Integration - Plugin + composable
✅ Unsubscribe Functions - Convenient subscription return
✅ Memory Efficient - Automatic history trimming
✅ Well Tested - Comprehensive test suite
This implementation provides production-ready type-safe event bus management!
// event-bus.ts
import {
EventPayloadMap,
EventHandler,
HistoryEntry,
IEventBus,
} from './types';
class EventBus<EventMap extends EventPayloadMap> implements IEventBus<EventMap> {
private listeners: Map<
keyof EventMap,
Set<EventHandler>
> = new Map();
private onceListeners: Map<
keyof EventMap,
Set<EventHandler>
> = new Map();
private history: Map<keyof EventMap, HistoryEntry[]> = new Map();
private maxHistorySize: Map<keyof EventMap, number> = new Map();
/**
* Subscribe to an event
* @param event - Event name
* @param handler - Handler function
* @returns Unsubscribe function
*/
on<K extends keyof EventMap>(
event: K,
handler: EventHandler<EventMap[K]>
): () => void {
if (!this.listeners.has(event)) {
this.listeners.set(event, new Set());
}
const handlers = this.listeners.get(event)!;
handlers.add(handler);
// Return unsubscribe function
return () => {
handlers.delete(handler);
};
}
/**
* Subscribe to an event once
* @param event - Event name
* @param handler - Handler function
* @returns Unsubscribe function
*/
once<K extends keyof EventMap>(
event: K,
handler: EventHandler<EventMap[K]>
): () => void {
if (!this.onceListeners.has(event)) {
this.onceListeners.set(event, new Set());
}
const onceHandlers = this.onceListeners.get(event)!;
onceHandlers.add(handler);
// Return unsubscribe function
return () => {
onceHandlers.delete(handler);
};
}
/**
* Unsubscribe from an event
* @param event - Event name
* @param handler - Optional: specific handler. If not provided, removes all handlers
*/
off<K extends keyof EventMap>(
event: K,
handler?: EventHandler<EventMap[K]>
): void {
if (handler) {
this.listeners.get(event)?.delete(handler);
this.onceListeners.get(event)?.delete(handler);
} else {
this.listeners.delete(event);
this.onceListeners.delete(event);
}
}
/**
* Emit an event
* @param event - Event name
* @param payload - Event payload
*/
async emit<K extends keyof EventMap>(
event: K,
payload: EventMap[K]
): Promise<void> {
// Record in history
this._recordHistory(event, payload);
// Call regular handlers
const handlers = Array.from(this.listeners.get(event) || []);
const promises = handlers.map((handler) =>
Promise.resolve().then(() => handler(payload))
);
// Call once handlers
const onceHandlers = Array.from(this.onceListeners.get(event) || []);
const oncePromises = onceHandlers.map((handler) =>
Promise.resolve()
.then(() => handler(payload))
.finally(() => {
this.onceListeners.get(event)?.delete(handler);
})
);
await Promise.all([...promises, ...oncePromises]);
}
/**
* Get history for an event
* @param event - Event name
* @param count - Optional: number of last events to retrieve
*/
getHistory<K extends keyof EventMap>(
event: K,
count?: number
): HistoryEntry<EventMap[K]>[] {
const events = this.history.get(event) || [];
if (count === undefined || count < 0) {
return [...events];
}
return events.slice(-count);
}
/**
* Replay history to a handler without subscribing
* @param event - Event name
* @param handler - Handler function
* @param count - Optional: number of last events to replay, defaults to all
*/
async replay<K extends keyof EventMap>(
event: K,
handler: EventHandler<EventMap[K]>,
count?: number
): Promise<void> {
const history = this.getHistory(event, count);
for (const entry of history) {
await Promise.resolve().then(() => handler(entry.payload));
}
}
/**
* Replay history and then subscribe to future events
* @param event - Event name
* @param handler - Handler function
* @param count - Optional: number of last events to replay
* @returns Unsubscribe function
*/
replayAndSubscribe<K extends keyof EventMap>(
event: K,
handler: EventHandler<EventMap[K]>,
count: number = -1
): () => void {
// Replay history first
this.replay(event, handler, count > 0 ? count : undefined);
// Then subscribe to new events
return this.on(event, handler);
}
/**
* Clear all subscribers for an event or all events
* @param event - Optional: specific event to clear
*/
clear<K extends keyof EventMap>(event?: K): void {
if (event) {
this.listeners.delete(event);
this.onceListeners.delete(event);
} else {
this.listeners.clear();
this.onceListeners.clear();
}
}
/**
* Clear history for an event or all events
* @param event - Optional: specific event
* @param maxSize - Optional: keep only last N items
*/
clearHistory<K extends keyof EventMap>(
event?: K,
maxSize?: number
): void {
if (event) {
if (maxSize !== undefined && maxSize > 0) {
const history = this.history.get(event);
if (history && history.length > maxSize) {
this.history.set(event, history.slice(-maxSize));
}
} else {
this.history.delete(event);
}
} else {
this.history.clear();
}
}
/**
* Set maximum history size for an event
* @param event - Event name
* @param size - Maximum number of entries to keep
*/
setMaxHistorySize<K extends keyof EventMap>(event: K, size: number): void {
if (size > 0) {
this.maxHistorySize.set(event, size);
this.clearHistory(event, size);
}
}
/**
* Get count of subscribers for an event
*/
getSubscriberCount<K extends keyof EventMap>(event: K): number {
const regular = this.listeners.get(event)?.size || 0;
const once = this.onceListeners.get(event)?.size || 0;
return regular + once;
}
/**
* Remove all subscribers from all events
*/
offAll(): void {
this.listeners.clear();
this.onceListeners.clear();
}
/**
* Private: Record event in history
*/
private _recordHistory<K extends keyof EventMap>(
event: K,
payload: EventMap[K]
): void {
if (!this.history.has(event)) {
this.history.set(event, []);
}
const events = this.history.get(event)!;
events.push({
payload,
timestamp: Date.now(),
});
// Enforce max size if set
const maxSize = this.maxHistorySize.get(event);
if (maxSize && events.length > maxSize) {
events.splice(0, events.length - maxSize);
}
}
}
export { EventBus };