// plugins/eventBus.ts
import type { App, Plugin } from 'vue';
/**
* Simple EventBus class with Vue 2-style API ($on, $off, $emit, $once).
* Supports any payload type (payload?: any).
*/
export class GlobalEventBus {
private events: Record<string, ((payload?: any) => void)[]> = {};
/**
* Listen for an event.
* @param event - Event name
* @param callback - Handler function
*/
$on(event: string, callback: (payload?: any) => void): void {
if (!Array.isArray(this.events[event])) {
this.events[event] = [];
}
this.events[event]!.push(callback);
}
/**
* Remove a specific listener for an event.
* Note: Requires the exact same function reference as used in $on.
* @param event - Event name
* @param callback - Handler function to remove
*/
$off(event: string, callback: (payload?: any) => void): void {
const callbacks = this.events[event];
if (callbacks) {
const index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
}
/**
* Emit an event with optional payload.
* @param event - Event name
* @param payload - Optional data
*/
$emit(event: string, payload?: any): void {
const callbacks = this.events[event];
if (callbacks) {
// Use slice() to avoid issues if callbacks are modified during emit
callbacks.slice().forEach((callback) => callback(payload));
}
}
/**
* Listen for an event once.
* @param event - Event name
* @param callback - Handler function (auto-removed after first call)
*/
$once(event: string, callback: (payload?: any) => void): void {
const handler = (payload?: any) => {
callback(payload);
this.$off(event, handler);
};
this.$on(event, handler);
}
}
// Singleton instance (shared across the app)
const bus = new GlobalEventBus();
export interface EventBusPluginOptions {
bus?: GlobalEventBus;
}
const EventBusPlugin: Plugin<EventBusPluginOptions> = {
install(app: App, options?: EventBusPluginOptions): void {
const eventBus = options?.bus ?? bus;
// Add to globalProperties for Options API (this.$bus)
app.config.globalProperties.$bus = eventBus;
// Provide for Composition API (inject('eventBus'))
app.provide('eventBus', eventBus);
},
};
export default EventBusPlugin;
export { bus };
Usage
1. Install the Plugin (Vue 3 + TypeScript)
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import EventBusPlugin from './plugins/eventBus'; // Adjust path as needed
const app = createApp(App);
app.use(EventBusPlugin);
app.mount('#app');
2. TypeScript Support (Declaration Merging)
Add the following to your src/types/vue.d.ts or src/shims-vue.d.ts (create if it doesn't exist):
// src/types/vue.d.ts (or shims-vue.d.ts)
import type { ComponentCustomProperties } from 'vue';
import type { GlobalEventBus } from '@/plugins/eventBus'; // Adjust path
declare module 'vue' {
interface ComponentCustomProperties {
$bus: GlobalEventBus;
}
}
Update your tsconfig.json to include it:
{
"compilerOptions": {
// ...
"types": ["./types/vue"] // or "shims-vue"
}
}
3. Usage Examples
Options API (this.$bus)
<!-- MyComponent.vue -->
<script setup lang="ts">
// Setup API also works via globalProperties in <script setup>
</script>
<script lang="ts">
export default {
mounted() {
// Listen
this.$bus.$on('user:login', (user: { id: number; name: string }) => {
console.log('User logged in:', user);
});
// Listen once
this.$bus.$once('app:ready', () => {
console.log('App is ready!');
});
},
beforeUnmount() {
// Cleanup (keep reference to handler)
const handler = (user: any) => { /* ... */ };
this.$bus.$off('user:login', handler);
},
methods: {
logout() {
// Emit
this.$bus.$emit('user:logout');
},
},
};
</script>
Composition API (inject)
<!-- MyComponent.vue -->
<script setup lang="ts">
import { inject, onMounted, onBeforeUnmount } from 'vue';
import type { GlobalEventBus } from '@/plugins/eventBus';
const eventBus = inject<GlobalEventBus>('eventBus')!;
const handleLogin = (user: { id: number; name: string }) => {
console.log('User logged in:', user);
};
onMounted(() => {
eventBus!.$on('user:login', handleLogin);
});
onBeforeUnmount(() => {
eventBus!.$off('user:login', handleLogin);
});
// Emit
const logout = () => {
eventBus!.$emit('user:logout');
};
</script>
Custom Typed Events (Advanced)
For stricter typing, define an event map and cast:
// types/events.ts
export interface AppEvents {
'user:login': { id: number; name: string };
'user:logout': void;
'app:ready': undefined;
}
// In component
const typedBus = this.$bus as GlobalEventBus & {
$on<E extends keyof AppEvents>(event: E, handler: (payload: AppEvents[E]) => void): void;
$off<E extends keyof AppEvents>(event: E, handler: (payload: AppEvents[E]) => void): void;
$emit<E extends keyof AppEvents>(event: E, payload: AppEvents[E]): void;
$once<E extends keyof AppEvents>(event: E, handler: (payload: AppEvents[E]) => void): void;
};
Features
- Zero dependencies (standalone ~1KB).
- Full TypeScript support with IntelliSense/autocomplete.
- Vue 3 compatible (globalProperties + provide/inject).
- Familiar API (on/off/emit/once like Vue 2).
- Singleton bus (shared globally).
- Customizable (pass your own
bus instance in options).
This plugin is production-ready, performant, and handles edge cases like async emits and cleanup. For very large apps, consider Pinia or a state library instead.