订阅发布模式

一、订阅发布模式--- node eventEmitter

require('events');
// 订阅发布模式
class EventEmitter {
  constructor() {
    this._events = {};
  }

  on(name, callback) {
    if (this._events[name]) {
      this._events[name].push(callback);
    } else {
      this._events[name] = [callback];
    }
  }

  emit(name) {
    if (this._events[name]) {
      this._events[name].forEach(cb => cb());
    }
  }

  remove(name, callback) {
    if (this._events[name]) {
      this._events[name] = this._events[name].filter(cb => cb !== callback);
    }
  }

  once(name, callback) {
    const fn = () => {
      callback();
      this.remove(name, fn);
    };
    this.on(name, fn);
  }
}

const event = new EventEmitter();

const func1 = () => {
  console.log('func1');
};
const func2 = () => {
  console.log('func2');
};
const func3 = () => {
  console.log('func3');
};
event.on('datas', func1);
event.on('datas', func2);
event.once('datas', func3);

event.emit('datas');
event.remove('datas', func1);
event.emit('datas');

 

上一篇:用Maven命令,把我们提前下载好的Jar包安装到本地的仓库。


下一篇:Hive学习笔记(1)基本操作