在这里结合了单例模式写了一个发布订阅者模式。

    1. class MyEvent {
    2. protected readonly store: { [key: string]: Function };
    3. private static instance: MyEvent;
    4. constructor() {
    5. if (!MyEvent.instance) {
    6. this.store = {}
    7. MyEvent.instance = this
    8. }
    9. return MyEvent.instance
    10. }
    11. $on(type: string, callBack: Function) {
    12. if (!this.store[type]) {
    13. this.store[type] = callBack
    14. }
    15. }
    16. $emit(type: string, data?: any) {
    17. if (!this.store[type]) {
    18. console.warn(`当前${type}没有被注册!`)
    19. } else {
    20. let fn = this.store[type]
    21. fn(data)
    22. }
    23. }
    24. $off(type: string) {
    25. delete this.store[type]
    26. }
    27. }
    28. let eve = new MyEvent()
    29. eve.$on("success",function(e){
    30. console.log(e)
    31. })
    32. eve.$emit("success",{detail:"ok"})

    为了体现封装继承多态,还可以继承 MyEvent 添加自己的一些方法。

    1. class MyAddEvent extends MyEvent {
    2. constructor() {
    3. super()
    4. }
    5. getEventStore() {
    6. console.log(this.store) // 可以获取 父类的store
    7. }
    8. }