手写发布订阅

实现的方法:

  • on 订阅事件
  • emit 发布事件
  • remove 取消发布
  • removeAll 取消某一类事件的所有订阅
  • once 只订阅一次

实现

  function EventEmitter() {
      this.events = {};
    };

    // 订阅函数
    EventEmitter.prototype.on = function (eventname, callback) {
      if (!this.events[eventname]) {
        this.events[eventname] = []
      };
      this.events[eventname].push(callback);
    };

    // 发布函数,区分事件类型
    EventEmitter.prototype.emit = function (eventname, ...args) {
      const fns = this.events[eventname] || [];
      fns.length > 0 && fns.forEach(fn => fn(...args));
    };

    //取消订阅
    EventEmitter.prototype.remove = function (eventname, callback) {
      if (Array.isArray(this.events[eventname])) {
        this.events[eventname] = this.events[eventname].filter(fn => fn !== callback);
      };
    };

    //取消某一类事件的全部订阅
    EventEmitter.prototype.removeAll = function (eventname) {
      delete this.events[eventname];
    };

    // 只订阅一次
    EventEmitter.prototype.once = function (eventname, callback) {
      const fn = (...rest) => {
        callback(...rest);
        this.removeAll(eventname);
      };
      this.on(eventname, fn)
    };

使用

  <button onclick="handleClick()">发布</button>
  <button onclick="remove()">取消订阅</button>
  
    const event = new EventEmitter();
  
    event.once('clickonce', (...res) => {
      console.log('clickonce事件触发', res);
    });

    event.on('click', (...res) => {
      console.log('click事件触发1', res);
    });

    event.on('dbclick', (...res) => {
      console.log('dbclick事件触发', res);
    });

    const handleClick = () => {
      event.emit('clickonce', 1);
      event.emit('click', 2);
      event.emit('dbclick', 3)
    };

    const remove = () => event.removeAll('click');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
发布订阅模式又称观察者模式,是一种常见的设计模式,它定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。下面是手写JavaScript发布订阅模式的一种实现方式: ```javascript function PubSub() { this.subscribers = {}; } PubSub.prototype.subscribe = function(event, callback) { if (!this.subscribers[event]) { this.subscribers[event] = []; } this.subscribers[event].push(callback); }; PubSub.prototype.unsubscribe = function(event, callback) { if (!this.subscribers[event]) { return; } var index = this.subscribers[event].indexOf(callback); if (index > -1) { this.subscribers[event].splice(index, 1); } }; PubSub.prototype.publish = function(event, data) { if (!this.subscribers[event]) { return; } this.subscribers[event].forEach(function(callback) { callback(data); }); }; ``` 使用方式如下: ```javascript var pubsub = new PubSub(); function callback1(data) { console.log('callback1:', data); } pubsub.subscribe('event1', callback1); function callback2(data) { console.log('callback2:', data); } pubsub.subscribe('event2', callback2); pubsub.publish('event1', { message: 'hello' }); pubsub.publish('event2', { message: 'world' }); pubsub.unsubscribe('event1', callback1); pubsub.publish('event1', { message: 'hello again' }); ``` 输出结果为: ``` callback1: {message: "hello"} callback2: {message: "world"} ``` 当调用 `publish` 方法时,订阅了该事件的所有回调函数都将被执行,并且可以传递一个数据对象作为参数。调用 `subscribe` 方法注册一个回调函数,当该事件被发布时,该回调函数将被执行。调用 `unsubscribe` 方法取消订阅。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值