javascript">/**
* 事件管理器
* ==========
*
* *单例模式singleton* 通用的事件管理工具,可以处理各种事件触发和回调。
*
* 1. 事件根据topic 分类。
* 2. 主题:即topic 。
* 3. 内部将所有的事件按照topic 为key、事件回调函数为value 的map 来存储。
* 4. subscribe: 订阅某事件。
* 5. trigger: 触发某事件。
*/
export class EventCenter {
/**
* 事件图。
*/
private _subscribeMap = new Map()
public static singleton: EventCenter = new EventCenter()
/**
* 订阅事件:增加一个事件到事件中心,同时将topic 添加到 topics 列表中。
*
* @param topic
* @param f 回调
*/
subscribe(topic, f) {
const events = this._subscribeMap.get(topic)
if (events) {
events.push(f)
} else {
this._subscribeMap.set(topic, [f])
}
}
/**
* 获取对应的事件列表。
*
* @param topic
*/
getEvents(topic) {
return this._subscribeMap.get(topic)
}
/**
* 触发事件:触发所有订阅该名称的事件。
*
* @param topic
* @param data
*/
trigger(topic, data) {
const events = this._subscribeMap.get(topic)
if (events) {
events.forEach((f) => {
f(data, topic)
})
}
}
}
订阅事件:
javascript">
EventCenter.singleton.subscribe('topic1', () => {
// ....
})
发布事件:
javascript">EventCenter.singleton.trigger('topic1', null)