zoukankan      html  css  js  c++  java
  • 发布者订阅者模式

    看了网上的资料感觉有两种实现,一种是发布的时候有关键字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
Copyright © 2011-2022 走看看