发布者订阅者模式

看了网上的资料感觉有两种实现,一种是发布的时候有关键字key,然后就执行所有订阅了key的事件,还有一种是没有key直接绑定在发布对象上,对象调用public方法然后执行所有绑定的函数

说到底区别就是前者是多个不同键值的数组存事件,后者是只有一个数组存所有时间,下面的代码是属于前一种

class EventEmitter{
    constructor(){
        this.EventList = {}
    }
    subscribe(key,fun){
        if(!this.EventList.hasOwnProperty(key)){
            this.EventList[key] = []
        }
        this.EventList[key].push(fun)
    }
    unsubscribe(key,fun){
        if(!this.EventList[key]) return

        this.EventList = this.EventList[key].filter((f)=>{
            if(f!=fun) return f
        })
    }
    public(key,arg){
        if(!this.EventList[key]){
            console.log('no respond event')
            return 
        }
        this.EventList[key].forEach(fun=>{
            fun(arg)
        })

    }
}
var EE = new EventEmitter()
var print = (data)=>{
    console.log(data)
}
EE.subscribe('done',print)
EE.public('done','12223')
EE.unsubscribe('done',print)
EE.public('done','12223')
原文地址:https://www.cnblogs.com/maskmtj/p/9355020.html