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

  • 相关阅读:
    PAT 甲级 1128 N Queens Puzzle
    HDU 1995 R-汉诺塔V
    PAT L1-039 古风排版
    PAT L2-028 秀恩爱分得快
    ZOJ 2060 A-Fibonacci Again
    HDU 2079 选课时间
    HDU 1016 Prime Ring Problem
    理论相关概念原理
    单播字符、字符串收发
    OSAL的原理
  • 原文地址:https://www.cnblogs.com/wulinzi/p/12988208.html
Copyright © 2011-2022 走看看