TypeScript(TS) 实现消息通知(发布订阅)
将执行函数放到 map 中,每次需要改变 调出 map 中的函数执行即可;
export class EventDispatcher {
private eventMap = new Map<string, Function>();
private static EMITTER :EventDispatcher;
public static getInstance():EventDispatcher {
if (!EventDispatcher.EMITTER ){
EventDispatcher.EMITTER = new EventDispatcher();
}
return EventDispatcher.EMITTER ;
}
private constructor() {
this.eventMap.clear();
}
/**
* 注册事件
* @param event
* @param callback
*/
on = (event: string, callback: Function) => {
this.eventMap.set(event, callback);
};
/**
* 发布消息
* @param event
* @param de
* @param args
*/
emit = (event: string, ...args: Array<any>) => {
if (!this.eventMap.get(event)) {
console.log('事件未注册', event, args);
return;
}
this.eventMap.get(event)!.apply(this, args)
};
}
使用方法
// 创建对象
public static readonly EMITTER:EventDispatcher = EventDispatcher.getInstance();
// 注册事件
EMITTER.on("event1", () => {
console.log('执行event1');
})
// 发送消息
EMITTER.emit("event1");
注销事件,只需将 map 中对象的键值对删除即可;