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.
Designing fully typed Vue 3 event bus plugin with replay
The plan defines a Vue 3 plugin providing a generic, strongly typed event bus—built without mitt—that attaches a typed $bus to app.config.globalProperties. It supports emitting typed events, subscribing with autocompletion based on event keys, and a replay feature delivering the last N events of a topic immediately to new subscribers. The implementation uses TypeScript mapped types, a class managing listeners and event histories capped by a configurable max buffer, and module augmentation to extend Vue component typings for seamless TS integration. The next step is to implement the complete plugin code and a usage example following this design.
Below is a minimal Vue 3 plugin that gives you a strongly‑typed event bus (no mitt) and a per‑topic replay buffer. The payload type autocompletes based on the event name, and new subscribers can ask for the last N events of that topic.
Define your event map: keys are event names, values are payload types.
ts
// events.d.ts (or any .ts file that's in your TS build)
export type MyEvents = {
'user:login': { id: string; name: string };
'chat:message': { from: string; text: string };
'counter:update': number;
};
Event bus implementation + plugin
ts
// typedEventBus.ts
import { App } from 'vue';
type EventMap = Record<string, any>;
export class TypedEventBus<T extends EventMap> {
private listeners = new Map<keyof T, Set<(payload: any) => void>>();
private history = new Map<keyof T, any[]>();
private maxHistory: number;
constructor(maxHistory = 10) {
this.maxHistory = maxHistory;
}
emit<K extends keyof T>(event: K, payload: T[K]): void {
// store history
const hist = this.history.get(event) ?? [];
hist.push(payload);
if (hist.length > this.maxHistory) {
hist.shift(); // keep last maxHistory items
}
this.history.set(event, hist);
// notify listeners
const handlers = this.listeners.get(event);
handlers?.forEach((fn) => fn(payload));
}
on<K extends keyof T>(
event: K,
handler: (payload: T[K]) => void,
options?: { replay?: number },
): () => void {
const set = this.listeners.get(event) ?? new Set();
set.add(handler);
this.listeners.set(event, set);
// replay last N events if requested
const replayCount = options?.replay ?? 0;
if (replayCount > 0) {
const hist = this.history.get(event) ?? [];
const toReplay = hist.slice(-replayCount); // last N
toReplay.forEach((payload) => handler(payload));
}
// return unsubscribe
return () => this.off(event, handler);
}
off<K extends keyof T>(event: K, handler: (payload: T[K]) => void): void {
const set = this.listeners.get(event);
if (!set) return;
set.delete(handler);
if (set.size === 0) {
this.listeners.delete(event);
}
}
clearHistory<K extends keyof T>(event?: K): void {
if (event) {
this.history.delete(event);
} else {
this.history.clear();
}
}
}
export function createTypedEventBus<T extends EventMap>(opts?: { maxHistory?: number }) {
const bus = new TypedEventBus<T>(opts?.maxHistory);
return {
install(app: App) {
app.config.globalProperties.$bus = bus;
},
bus,
};
}
Register plugin and augment Vue types
ts
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { createTypedEventBus } from './typedEventBus';
import type { MyEvents } from './events';
const eventBusPlugin = createTypedEventBus<MyEvents>({ maxHistory: 20 });
const app = createApp(App);
app.use(eventBusPlugin);
app.mount('#app');
// typed shim so `this.$bus` is typed in components
declare module 'vue' {
interface ComponentCustomProperties {
$bus: TypedEventBus<MyEvents>;
}
}
Usage
Options API:
ts
export default {
mounted() {
// Emits are typed by event name
this.$bus.emit('counter:update', 42);
// this.$bus.emit('counter:update', 'oops'); // TS error
// Subscribe with replay of last 3 chat messages
const off = this.$bus.on(
'chat:message',
(msg) => console.log(msg.from, msg.text),
{ replay: 3 },
);
// Later, to unsubscribe:
// off();
},
};
Composition API:
ts
import { getCurrentInstance, onBeforeUnmount } from 'vue';
export default {
setup() {
const bus = getCurrentInstance()!.proxy!.$bus; // or export bus from plugin file
const stop = bus.on(
'user:login',
(payload) => {
console.log('Logged in:', payload.id, payload.name);
},
{ replay: 1 }, // get last login if available
);
onBeforeUnmount(() => {
stop();
});
},
};
emit(event, payload) is fully type‑safe and autocompletes payload based on the event name.
on(event, handler, { replay: N }) will immediately invoke handler with the last N payloads for that event (if any), then listen for future ones.
maxHistory controls how many events per topic are stored for potential replay.