JS发布订阅模式封装(纯手工)

发布订阅模式是JS常用的设计模式,在面试中也会经常遇到,以下是我的手写实现方式,经测试效果不错,小伙伴们们可以直接拷贝使用。

类式定义方式

class EventEmitter {
  handlers = {};

  on(type, handler, once = false) {
    if (!this.handlers[type]) {
      this.handlers[type] = [];
    }

    if (!this.handlers[type].includes(handler)) {
      this.handlers[type].push(handler);
      handler.once = once;
    }
  }

  once(type, hanlder) {
    this.on(type, hanlder, true);
  }

  off(type, handler) {
    if (this.handlers[type]) {
      this.handlers[type] = this.handlers[type].filter((h) => h !== handler);
    }
  }

  trigger(type) {
    if (this.handlers[type]) {
      this.handlers[type].forEach((handler) => {
        handler.call(this);

        if (handler.once) {
          this.off(type, handler);
        }
      });
    }
  }
}

测试和打印

const ev = new EventEmitter();
function handler1() {
  console.log("handler1");
}
function handler2() {
  console.log("handler2");
}
function handler3() {
  console.log("handler3");
}
ev.on("test", handler1);
ev.on("test", handler2);
ev.on("test", handler3);
ev.trigger("test");
ev.trigger("test");

输出如下:

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容