zoukankan      html  css  js  c++  java
  • 事件总线(发布订阅模式)

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <script>
          class EventEmitter {
            constructor() {
              this.cache = {};
            }
            on(name, fn) {
              if (this.cache[name]) {
                this.cache[name].push(fn);
              } else {
                this.cache[name] = [fn];
              }
            }
            off(name, fn) {
              let tasks = this.cache[name];
              if (tasks) {
                const index = tasks.findIndex((f) => f === fn || f.callback === fn);
                if (index >= 0) {
                  tasks.splice(index, 1);
                }
              }
            }
            emit(name, once = false, ...args) {
              if (this.cache[name]) {
                let tasks = this.cache[name].slice();
                for (const fn of tasks) {
                  fn(...args);
                }
                if (once) {
                  delete this.cache[name];
                }
              }
            }
          }
    
          let eb = new EventEmitter();
          let f1 = function (name, age) {
            console.log(name + "f1 " + age);
          };
          let f2 = function (name, age) {
            console.log(name + "f2 " + age);
          };
          eb.on('aaa',f1)
          eb.off('aaa',f1)
          eb.on('aaa',f1)
          eb.on('aaa',f2)
          eb.on('bbb',f2)
          eb.emit('aaa',false,'hehe',12)
        </script>
      </body>
    </html>
    
  • 相关阅读:
    java基础英语---第二天
    树莓派的版本
    Linux系统下安装.deb文件
    在Raspberry上安装ROS
    树莓派文件权限的转换
    树莓派中Linux的相关命令
    raspberry连接ssh和vnc
    链表的建立及释放
    一些小细节问题
    关于构建二维动态内存(堆)及释放
  • 原文地址:https://www.cnblogs.com/samsara-yx/p/14621117.html
Copyright © 2011-2022 走看看