在这里结合了单例模式写了一个发布订阅者模式。
class MyEvent {protected readonly store: { [key: string]: Function };private static instance: MyEvent;constructor() {if (!MyEvent.instance) {this.store = {}MyEvent.instance = this}return MyEvent.instance}$on(type: string, callBack: Function) {if (!this.store[type]) {this.store[type] = callBack}}$emit(type: string, data?: any) {if (!this.store[type]) {console.warn(`当前${type}没有被注册!`)} else {let fn = this.store[type]fn(data)}}$off(type: string) {delete this.store[type]}}let eve = new MyEvent()eve.$on("success",function(e){console.log(e)})eve.$emit("success",{detail:"ok"})
为了体现封装继承多态,还可以继承 MyEvent 添加自己的一些方法。
class MyAddEvent extends MyEvent {constructor() {super()}getEventStore() {console.log(this.store) // 可以获取 父类的store}}
