zoukankan      html  css  js  c++  java
  • 手写一个简单的发布者订阅者模式

    手写一个发布者订阅者模式:

     // 手写发布订阅模式 EventEmitter
          class EventEmitter {
            constructor() {
              this.events = {};
            }
            // 实现订阅
            on(type, callBack) {
              if (!this.events) this.events = Object.create(null);
    
              if (!this.events[type]) {
                this.events[type] = [callBack];
              } else {
                this.events[type].push(callBack);
              }
            }
            // 删除订阅
            off(type, callBack) {
              if (!this.events[type]) return;
              this.events[type] = this.events[type].filter(item => {
                return item !== callBack;
              });
            }
            // 只执行一次订阅事件
            once(type, callBack) {
              function fn() {
                callBack();
                this.off(type, fn);
              }
              this.on(type, fn);
            }
            // 触发事件
            emit(type, ...rest) {
              this.events[type] &&
                this.events[type].forEach(fn => fn.apply(this, rest));
            }
          }
    // 使用如下
          const event = new EventEmitter();
    
          const handle = (...rest) => {
            console.log(rest);
          };
    
          event.on("click", handle);
    
          event.emit("click", 1, 2, 3, 4);
    
          event.off("click", handle);
    
          event.emit("click", 1, 2);
    
          event.once("dbClick", () => {
            console.log(123456);
          });
          event.emit("dbClick");
          event.emit("dbClick");

    Ok

  • 相关阅读:
    求矩形最大面积
    异或相关知识
    算法模板-线段树区间最值
    矩阵递推关系的建立 and 矩阵快速幂
    二分答案模板
    关于STL,set,vector,map的时间
    域名解析
    CDN配置
    CDN的工作原理及好处
    打赏
  • 原文地址:https://www.cnblogs.com/wulinzi/p/12988208.html
Copyright © 2011-2022 走看看