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);
  • 相关阅读:
    第八章 线性时间排序
    第七章 快速排序
    第六章 堆排序
    第四章 分治策略
    第二章 算法基础
    第一章 算法在计算中的作用
    opencv —— cornerSubPix 亚像素级角点检测
    opencv —— Shi-Tomasi 角点检测
    .NET List<T>Conat vs AddRange
    自定义组装json对象
  • 原文地址:https://www.cnblogs.com/mili3/p/14504099.html
Copyright © 2011-2022 走看看