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')
  • 相关阅读:
    Moving Price and Standard Price
    Partner function解析
    [ABAP] ABAP中定义和呼叫宏
    ABAP
    Words Learning~~(1-3)
    Words Learning~~(1-2)
    Words Learning~~(1-1)
    SQLSERVER如何查看索引缺失
    Material Stock manage T-code
    远程重启
  • 原文地址:https://www.cnblogs.com/maskmtj/p/9355020.html
Copyright © 2011-2022 走看看