zoukankan      html  css  js  c++  java
  • 手写eventhub(发布订阅)

            //手写eventhub(发布订阅)
            //    核心思路:1.使用一个对象作为缓存
            //    2.on负责把方法发布到缓存的eventName数组中
            //    3.emit负责遍历eventName中的方法数组
            //    4.off负责清除缓存中的方法
            class EventHub {
                cache={}
                on(eventName,fn){
                    this.cache[eventName]=this.cache[eventName]||[]
                    this.cache[eventName].push(fn)
                }
                emit(eventName){
                    this.cache[eventName]=this.cache[eventName]||[]
                    this.cache[eventName].forEach(fn=>fn())
                }
                off(eventName,fn){
                    const index=this.cache[eventName].indexOf(fn);
                    if(index>-1){
                        this.cache[eventName][index]=null
                    }
                }
            }

            function fnn(){
                console.log("执行发布订阅了奥");
            }
            let ev=new EventHub();
            ev.on("test",fnn)
            ev.emit("test");
            ev.off("test",fnn);
  • 相关阅读:
    PredictionIO+Universal Recommender快速开发部署推荐引擎的问题总结(1)
    SpringJDBC的JdbcTemplate在MySQL5.7下不支持子查询的问题
    POP3接收邮件
    发送邮件
    电子邮件介绍
    线程优先级队列
    线程同步
    threading模块
    _thread模块
    使用线程
  • 原文地址:https://www.cnblogs.com/mili3/p/14504099.html
Copyright © 2011-2022 走看看