提交 6be9fb23 编写于 作者: 沐夕花开's avatar 沐夕花开

简易版EventBus

上级
class EventBus {
constructor() {
this.eventsCache = {}
this.uid = 0
}
$on(key, callback) {
if (!this.eventsCache[key]) {
this.eventsCache[key] = []
}
const uid = ++this.uid
this.eventsCache[key].push({ uid, callback })
return uid
}
$emit(key, ...args) {
if (!this.eventsCache[key]) return
let events = this.eventsCache[key]
events.forEach(item => {
item.callback(...args)
if (item.isOnce) {
this.$off(key, item.uid)
}
});
}
$off(key, uid) {
const events = this.eventsCache[key]
if (!events) {
console.log(`事件${key}不存在`)
return
}
if (!uid) {
// 不传递uid,则清除当前 key 下所有的事件
delete this.eventsCache[key]
} else {
let eventIdx = events.findIndex(item => item.uid === uid)
if (eventIdx < 0) {
console.log(`事件${key}监听列表中不存在id为${uid}的回调`)
return
}
// 移除当前uid的回调
events.splice(eventIdx, 1)
// 如果长度为0, 则移除
if (!events.length) {
delete this.eventsCache[key]
}
}
}
$once(key, ...args) {
const retId = this.$on(key, ...args)
let thisIdx = this.eventsCache[key].findIndex(item => item.uid === retId)
// 添加 isOnce 标记
this.eventsCache[key][thisIdx].isOnce = true
// 返回 uid
return retId
}
}
const eventBus = new EventBus()
export default eventBus
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册