5 changed files with 85 additions and 51 deletions
@ -0,0 +1,54 @@ |
|||||
|
/** |
||||
|
* 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() |
Loading…
Reference in new issue