JS 手写: 发布订阅 (Publish/Subscribe & EventBus)

2023-05-17 15:16:36 浏览数 (3)

# EventEmit

代码语言:javascript复制
export default class EventEmitter {
  constructor () {
    this.events = {};
    this.maxListeners = 10;
  }

  on (eventName, listener) {
    if (this.events[eventName]) {
      if (this.events[eventName].length >= this.maxListeners) {
        console.warn(`EventEmitter: maxListeners exceeded.`);
        return;
      }
      this.events[eventName].push(listener);
    } else {
      this.events[eventName] = [];
      this.events[eventName].push(listener);
    }
  }

  emit (eventName, ...rest) {
    if (this.events[eventName]) {
      this.events[eventName].map(fn => fn.apply(this, rest));
    }
  }

  removeListener (eventName, listener) {
    if (this.events[eventName]) {
      delete this.events[eventName];
    }
  }

  removeAllListeners () {
    this.events = {};
  }
}

使用

代码语言:javascript复制
import EventEmit from './EventEmit';

let DeviceEventEmitter = new EventEmit();

DeviceEventEmitter.on('event', (param1, param2) => {
  console.log(param1, param2);
});

DeviceEventEmitter.emit('event', 'param1', 'param2'); // param1 param2
DeviceEventEmitter.removeListener('event');

# EventBus

代码语言:javascript复制
class EventBus {
  constructor () {
    this.events = this.events || {};
  }

  $on (eventName, callback) {
    if (this.events[eventName]) {
      this.events[eventName].push(callback);
    } else {
      this.events[eventName] = [];
      this.events[eventName].push(callback);
    }
  }

  $emit (eventName, ...rest) {
    if (this.events[eventName]) {
      this.events[eventName].map(fn => fn.apply(this, rest));
    }
  }

  $once (eventName, callback) {
    const self = this;
    const onceCallback = function () {
      callback.apply(self, arguments);
      self.$off(eventName);
    };
    this.$on(eventName, onceCallback);
  }

  $off (eventName) {
    if (eventName) {
      if (this.events[eventName]) {
        delete this.events[eventName];
      }
    } else {
      this.events = {};
    }
  }
}

0 人点赞