75 lines
1.4 KiB
TypeScript
75 lines
1.4 KiB
TypeScript
// plugins/eventBus.js
|
|
import { defineNuxtPlugin } from "#app";
|
|
|
|
class EventBus {
|
|
constructor() {
|
|
this.events = {};
|
|
}
|
|
|
|
emit(event, ...args) {
|
|
if (this.events[event]) {
|
|
this.events[event].forEach((callback) => callback(...args));
|
|
}
|
|
}
|
|
|
|
on(event, callback) {
|
|
if (!this.events[event]) {
|
|
this.events[event] = [];
|
|
}
|
|
this.events[event].push(callback);
|
|
}
|
|
}
|
|
|
|
// Create a singleton instance of EventBus
|
|
const eventBus = new EventBus();
|
|
|
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
// Inject the eventBus instance into the Nuxt app context
|
|
nuxtApp.provide("eventBus", eventBus);
|
|
});
|
|
// ******* Using the mitt library ******
|
|
// import mitt from "mitt";
|
|
|
|
// const eventBus = mitt();
|
|
|
|
// export default eventBus;
|
|
|
|
// Emit an event
|
|
|
|
// js
|
|
// import eventBus from '~/eventBus'
|
|
|
|
// eventBus.emit('my-event', 'Hello, world!')
|
|
|
|
// Listen for an event
|
|
|
|
// js
|
|
// import eventBus from '~/eventBus'
|
|
|
|
// eventBus.on('my-event', (message) => {
|
|
// console.log(message)
|
|
// })
|
|
|
|
// ****** Using the useEventBus composable*********
|
|
// <template>
|
|
// <!-- ... -->
|
|
// </template>
|
|
|
|
// <script>
|
|
// import { useEventBus } from '#app'
|
|
|
|
// export default {
|
|
// setup() {
|
|
// const eventBus = useEventBus()
|
|
|
|
// eventBus.on('my-event', () => {
|
|
// console.log('Received event!')
|
|
// })
|
|
|
|
// return {
|
|
// // ...
|
|
// }
|
|
// }
|
|
// }
|
|
// </script>
|