实现EventEmitter

'use strict';
//被观察的对象定义
class EventEmitter {
  constructor() {
    this.listeners = new Map();
  }
  addListener(label, cb) {
    this.listeners.has(label) || this.listeners.set(label, []);
    this.listeners.get(label).push(cb);
  }
  removeListener(label, cb){
    let listeners = this.listeners.get(label);
    let index;
    if(listeners && listeners.length){
      index = listeners.reduce((i, listener, index) => {
        return (isFunction(listener) && listener === cb) ? i = index : i;
      }, -1);
    }
    if(inex > -1){
      listeners.splice(index, 1);
      this.listeners.set(label, listeners);
      return true;
    }

    return false;
  }
  emit(label, ...args){
    let listeners = this.listeners.get(label);
    if(listeners && listeners.length) {
      listeners.forEach((listener)=>{
        listener(...args);
      });
      return true;
    }

    return false;
  }
}

//观察者
class Observer {
  constructor(id, subject) {
    this.id = id;
    this.subject = subject;
  }
  on(label, cb) {
    this.subject.addListener(label, cb);
  }
}

let observable = new EventEmitter();
let [o1, o2] = [
  new Observer(1, observable),
  new Observer(2, observable)
];

o1.on('e1', (data) => {
  console.log(`${o1.id} observered data`, data);
});
o2.on('e2', (data) => {
  console.log(`${o2.id} observered data`, data);
});

observable.emit('e1', [1,2,3]);
observable.emit('e2', {a:1,b:2});

你可能感兴趣的:(实现EventEmitter)