美文网首页
JS发布订阅模式封装(纯手工)

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

作者: 硅谷干货 | 来源:发表于2024-03-08 22:03 被阅读0次

发布订阅模式是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

相关文章

  • js的设计模式

    工厂模式 es6创建类模式: 单例模式: jquery发布订阅者模式: 因为jquery有缺陷,自己封装发布订阅者...

  • JS发布-订阅模式

    发布-订阅模式广泛应用于异步编程中,这是一种替代传递回调函数的方案。 现实中的例子: 小明想买房,到了售楼处被告知...

  • js 发布订阅模式

    发布订阅模式:订阅者(Subscriber)把自己想订阅的事件注册(Subscribe)到调度中心(Topic),...

  • 一份头条前端面试准备[整理稿]

    JS打乱数组 JS ajax JS bind 实现 懒加载 JS实现promise JS发布订阅模式 JSONP ...

  • 手写简单的vue双向绑定

    JS:仿vue数据初始化 核心:发布订阅者模式

  • 多异步之间的协作

    《深入浅出 Node.js》阅读随笔 Node.js 的中发布/订阅模式,一般用于解决一次发布对应多次订阅的情况。...

  • JS设计模式--发布/订阅模式

    一、前言 JS语言的执行环境是“单线程”,所以任务是一个一个进行执行,如果任务多就需要排队。如果任务多,浏览器加载...

  • 【JS基础】订阅发布模式

    最 新:https://www.zybuluo.com/c-Ku/note/934090 代码示例

  • js实现发布订阅模式

    发布订阅模式指的是希望接收通知的对象(Subscriber)基于一个主题通过自定义事件订阅主题,被激活事件的对象(...

  • JS设计模式-发布订阅

    发布订阅 比如一个公众号可以被多个用户同时订阅,当公众号有新增内容时候,只要发布就好了,用户就能接收到最新的内容。...

网友评论

      本文标题:JS发布订阅模式封装(纯手工)

      本文链接:https://www.haomeiwen.com/subject/lbsyzdtx.html