锦水居民端小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

54 lines
1.3 KiB

/**
* EventBus 全局事件总线
* on(msgName, func) 订阅消息 msgName订阅的事件名称 func 事件回调
* once(msgName, func) 仅订阅一次消息 后订阅的会替换前面订阅的消息
* emit(msgName,data) 发布消息 msgName消息名称 data-数据
* off(msgName) 移除消息
*/
class EventBus {
constructor () {
this.msgQueues = {}
}
// 将消息 绑定到 消息队列中
on (msgName, func) {
if (this.msgQueues[msgName]) {
if (typeof this.msgQueues[msgName] === "function") {
this.msgQueues[msgName] = [this.msgQueues[msgName], func]
} else {
this.msgQueues[msgName] = [...this.msgQueues[msgName], func]
}
} else {
this.msgQueues[msgName] = func;
}
}
// 消息队列中仅保存一个消息
once (msgName, func) {
this.msgQueues[msgName] = func
}
// 发送消息
emit (msgName, data = "") {
if (!this.msgQueues[msgName]) {
return
}
if (typeof this.msgQueues[msgName] === "function") {
this.msgQueues[msgName](data)
} else {
this.msgQueues[msgName].forEach(fn => fn(data))
}
}
// 移除消息
off (msgName) {
if (!this.msgQueues[msgName]) {
return
}
delete this.msgQueues[msgName]
}
}
export default new EventBus()