Continuing from the previous article, because the $on and $off methods of instances have been removed in Vue3, this time we will implement an EventBus widget and encapsulate it into a class for easy invocation.
singleton pattern
In a Vue application, we only need the singleton pattern of this class to manage events, so it should look like this:
class Listener {
constructor() {
this.name = "Listener"
this.store = {}
}
static getInstance() {
if (!Listener.instance) {
Listener.instance = new Listener()
}
return Listener.instance
}
/**
* 同一个事件可多次注册,可能触发时执行多次
* @param evtName
* @param cb
*/
$on(evtName, cb) {
if (typeof cb !== 'function') {
console.error(`[${this.name}] can't listen event:${evtName}, cb is not a function`)
return
}
if (!(evtName in this.store)) {
this.store[evtName] = []
}
this.store[evtName].push(cb)
console.log(`[${this.name}] listen on event:${evtName}, cb: ${cb.name}`)
}
$emit(evtName, ...data) {
if (evtName in this.store) {
this.store[evtName].forEach(cb => {
cb(...data)
})
} else {
console.error(`[${this.name}] could not found event:${evtName}`)
}
}
/**
* 卸载一个事件,如果没有传入cb会被所有cb都清除
* @param evtName
* @param cb
*/
$off(evtName, cb) {
if (evtName in this.store) {
if (cb) {
const index = this.store[evtName].indexOf(cb)
if (index > -1) {
this.store[evtName].splice(index, 1)
console.log(`[${this.name}] remove event:${evtName} cb: ${cb.name}`)
}
return
}
delete this.store[evtName]
console.log(`[${this.name}] deleted event:${evtName}`)
return null
}
console.warn(`[${this.name}] event:${evtName} not exist`)
}
}
export const VueListener = {
install: (Vue) => {
Vue.prototype.$listener = Listener.getInstance()
}
}
export const MyListener = Listener.getInstance()
As can be seen from the export at the end of the code, we can use it as a vue plugin or as a js library.
npm install
In order to facilitate installation and use, I have published it on the official npm website, which can be directly added to the project to use listener_leo
npm i listener_leo --save
// or
yarn add listener_leo
Instructions:
import Vue from 'vue'
import VueListener from 'listener_leo'
Vue.use(VueListener)
So it can be used in the component:
this.$listener.$emit()
this.$listener.$on()
this.$listener.$off()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。