Conceptualizing Event Bus Plugin
\n\n
I'm starting to home in on the core functionality. Initial focus: Ensuring this plugin integrates cleanly with Vue 3. The design needs to expose a straightforward API for both event emission and listening. I'm exploring various implementations, leaning towards a minimal, performant approach. Considering the structure of the plugin, I'm thinking about the most efficient methods for managing event subscriptions.
Planning Plugin Integration Steps
\n\n
Now I'm diving into the architectural specifics. The plugin's foundational elements are taking shape. I'm prioritizing TypeScript integration to ensure a type-safe event system. Currently, I'm focusing on defining the interfaces and types that will govern event names and their payloads, aiming for a flexible, yet strongly-typed design. I am also working through the logic of how it will integrate with a Vue app via an install method.
Outlining Event Type Definitions
\n\n
I'm now solidifying the type definitions. It's crucial for users to define their event schema. Thinking about module augmentation in TypeScript (.d.ts files). This allows users to declare their specific event names and payload types. Considering the best approach for seamless integration. The goal: Provide a straightforward way to extend the event types within a Vue project. Currently, I'm sketching out the structure of these declaration files.
Implementing the EventBus Class
\n\n
My focus is now entirely on the core implementation. I'm actively translating the class blueprint into functional code. Methods for subscribing to and emitting events are under active construction. Considering the use of a Map to manage event subscriptions to optimize performance. I'm taking steps to ensure efficient handling of multiple event listeners and ensuring that event payloads are correctly typed. I am testing it mentally.
Analyzing Vue Plugin Integration
\n\n
I'm now deep in the core logic. Specifically, I'm analyzing the potential use of a Map to hold event subscriptions. Considering the most performant methods for event management. Also, I'm reviewing the structure for both the on and emit methods within the event bus class. I'm focusing on ensuring type safety during event emission.
Defining Type Safety Approaches
\n\n
My current thinking is focused on type safety. Considering different methods to ensure correct event emission and listening. I'm prioritizing the creation of a robust EventMap type. Exploring how to leverage TypeScript's generics and module augmentation to provide a highly typed solution. I'm now structuring the plugin to allow developers to easily define their specific event types.
Here is a complete, robust implementation of a Vue 3 Event Bus Plugin with strict TypeScript support.
Since Vue 3 removed the $on, $off, and $emit instance methods, we will create a lightweight, dependency-free event emitter class and wrap it in a Vue plugin that supports both the Composition API and the Options API.
1. The Implementation (eventBus.ts)
This file contains the logic for the bus, the type definitions, and the Vue plugin installer.
import { App, inject, Plugin, InjectionKey } from 'vue';
// 1. Define a generic type for our Event Map
// Key = Event Name, Value = Payload Type
export type EventMap = Record<string, any>;
// 2. The Event Bus Class definition
export class TypedEventBus<T extends EventMap> {
private listeners: Map<keyof T, Set<(payload: any) => void>>;
constructor() {
this.listeners = new Map();
}
// Register an event handler
on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): void {
if (!this.listeners.has(event)) {
this.listeners.set(event, new Set());
}
this.listeners.get(event)!.add(handler);
}
// Remove an event handler
off<K extends keyof T>(event: K, handler: (payload: T[K]) => void): void {
const handlers = this.listeners.get(event);
if (handlers) {
handlers.delete(handler);
}
}
// Dispatch an event
emit<K extends keyof T>(event: K, payload: T[K]): void {
const handlers = this.listeners.get(event);
if (handlers) {
handlers.forEach((handler) => handler(payload));
}
}
// Clear all listeners (useful for cleanup)
allClear(): void {
this.listeners.clear();
}
}
// 3. Define the Injection Key
export const EventBusKey: InjectionKey<TypedEventBus<any>> = Symbol('EventBus');
// 4. Create the Plugin
export function createEventBus<E extends EventMap>() {
const bus = new TypedEventBus<E>();
return {
install(app: App) {
// Provide for Composition API
app.provide(EventBusKey, bus);
// Attach to Global Properties for Options API ($bus)
app.config.globalProperties.$bus = bus;
},
globalBus: bus // expose the instance directly if needed outside components
};
}
// 5. Composition API Hook
export function useEventBus<E extends EventMap>(): TypedEventBus<E> {
const bus = inject(EventBusKey);
if (!bus) {
throw new Error('Event Bus not provided. Did you install the plugin?');
}
return bus as TypedEventBus<E>;
}
2. Define Your Events (types.ts)
To make TypeScript work its magic, you need to define the shape of your events in your application.
// types/events.ts
export interface AppEvents {
// Event Name : Payload Type
'user:login': { userId: number; name: string };
'sidebar:toggle': boolean;
'toast:show': { message: string; type: 'success' | 'error' };
'app:reset': void; // undefined payload
}
3. Installation (main.ts)
Register the plugin in your main entry file.
import { createApp } from 'vue';
import App from './App.vue';
import { createEventBus } from './utils/eventBus';
import { AppEvents } from './types/events';
const app = createApp(App);
// Create the specific instance of the bus with your types
const busPlugin = createEventBus<AppEvents>();
app.use(busPlugin);
app.mount('#app');
// Extended Type Augmentation for Options API (Optional)
declare module '@vue/runtime-core' {
import { TypedEventBus } from './utils/eventBus';
interface ComponentCustomProperties {
$bus: TypedEventBus<AppEvents>;
}
}
4. Usage: Composition API (Recommended)
Here is how to use it inside a setup block. Notice how TypeScript will autocomplete event names and validate payloads.
<script setup lang="ts">
import { onUnmounted } from 'vue';
import { useEventBus } from './utils/eventBus';
import { AppEvents } from './types/events';
// Inject with types
const bus = useEventBus<AppEvents>();
// 1. EMITTING
function handleLogin() {
// TS Error: Property 'age' is missing
// bus.emit('user:login', { name: 'John' });
// Correct
bus.emit('user:login', { userId: 1, name: 'John' });
// Correct
bus.emit('sidebar:toggle', true);
}
// 2. LISTENING
const onToast = (payload: { message: string; type: 'success' | 'error' }) => {
console.log(payload.message);
};
// Register listener
bus.on('toast:show', onToast);
// Cleanup is important!
onUnmounted(() => {
bus.off('toast:show', onToast);
});
</script>
5. Usage: Options API (Legacy)
If you are using the Options API, the bus is available via this.$bus.
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
mounted() {
// Autocomplete works here thanks to the module augmentation in main.ts
this.$bus.on('sidebar:toggle', this.handleSidebar);
},
beforeUnmount() {
this.$bus.off('sidebar:toggle', this.handleSidebar);
},
methods: {
handleSidebar(isOpen: boolean) {
console.log('Sidebar is', isOpen);
},
triggerLogin() {
this.$bus.emit('user:login', { userId: 5, name: 'Jane' });
}
}
});
</script>
Key Features of this Solution:
- Strict Typing: You cannot emit an event that doesn't exist, and you cannot pass the wrong payload data type.
- Dependency Free: Uses native
Map, Set, and Vue's provide/inject. No mitt or tiny-emitter required (though logic is similar).
- Memory Management: Uses
Set to prevent duplicate handlers for the same function and provides off for cleanup.
- Hybrid Support: Works perfectly with
<script setup> and defineComponent.