I’ve created small library that I use for Vue 3 apps
How to use
Factory way
import eventBus from './eventBus'
// # addEventListener
eventBus.$on('message', console.log.bind(console, 'message:'))
const temporaryEvent = console.log.bind(console, 'temporary:')
eventBus.$on('temporary', temporaryEvent)
// # removeEventListener
eventBus.$off('temporary', temporaryEvent)
// # dispatchEvent
eventBus.$emit('message', 'Hello world')
// -> message: Hello world
eventBus.$emit('message', { name: 'Anna', age: 21 })
// -> {name: 'Anna', age: 21}
// # destroy events
eventBus.$destroy()
eventBus.$emit('message', 'This should not log after destroy')
// ->
Class way
import { EventBus } from './createEventBus'
import eventBus from './eventBus'
// # Check instance
console.log(eventBus instanceof EventBus)
// -> true
// # addEventListener
eventBus.$on('message', console.log.bind(console, 'message:'))
const temporaryEvent = console.log.bind(console, 'temporary:')
eventBus.$on('temporary', temporaryEvent)
// # removeEventListener
eventBus.$off('temporary', temporaryEvent)
// # dispatchEvent
eventBus.$emit('message', 'Hello world')
// -> message: Hello world
eventBus.$emit('message', { name: 'Anna', age: 21 })
// -> {name: 'Anna', age: 21}
// # destroy events
eventBus.$destroy()
eventBus.$emit('message', 'This should not log after destroy')
// ->
Vue Option API way
No, I don’t like over-hyped Composition API
import { createApp } form 'vue'
import HelloWorld from './HelloWorld.vue'
const template = document.createElement('template')
const app = createApp(vueOjbject, props)
const proxy = app.mount(template) // Proxy Object
// attach addEventListener
proxy.$$on('tick', data => {
console.log('on tick:', data)
})
// -> on tick: Tick Tock
// -> on tick: Tick Tock
// -> on tick: Tick Tock