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);
  • 相关阅读:
    什么是二进制补码
    第四章 VB程序的控制结构
    第三章 VB的程序设计基础
    C#學習基礎方法
    C#學習基礎繼承
    C#學習基礎變量和常量
    C#學習基礎域和屬性
    第八章 VB中ActiveX控件的使用
    写给WEB2.0的站长 不仅仅是泼冷水(转)
    常见错误和难点分析
  • 原文地址:https://www.cnblogs.com/mili3/p/14504099.html
Copyright © 2011-2022 走看看