JS手写练习随笔-20221211.1 ---- 事件中心(发布订阅)

发布订阅事件中心的实现

// TS

复制代码
class EventEmitter {
  // 事件中心
  private store: Record<string, Function[]>;

  constructor() {
    this.store = {};  
  }

  /**
   * 为某种类型的事件添加回调/处理函数
   */
  on(type: string, handler: Function) {
    // 如果已有该"type"的记录
    if (Array.isArray(this.store[type])) {
      this.store[type].push(handler);
    } 
    // 没有则初始化一个
    else {
      this.store[type] = [handler];
    }
  }

  /**
   * 清除某种类型的事件上特定的处理函数
   */
  off(type: string, handler: Function) {
    if (this.store[type] === undefined || this.store[type].length === 0) {
      return;
    }
    this.store[type] = this.store[type].filter((fn: Function) => {
      return fn !== handler;
    });
  }

  /**
   * 为某种类型的事件添加一次性的回调/处理函数
   */
  once(type: string, handler: Function) {
    const onceFn = () => {
      handler();
      this.off(type, onceFn);
    };
    this.on(type, onceFn);
  }

  /**
   * 触发相应类型的事件
   */
  emit(type: string, ...params: Parameters<any>) {
    if (this.store[type] === undefined || this.store[type].length === 0) {
      return;
    }
    this.store[type].forEach(fn => {
      fn.apply(this, params);
    });
  }
}
复制代码

 

posted @   樊顺  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
历史上的今天:
2021-12-11 关于window.location的细节
点击右上角即可分享
微信分享提示