Simple eventEmitter

实现目标

Event.on("test", function(result) {
  console.log(result);
})
Event.on("test", function(result) {
  console.log("test");
})
Event.emit("test", "hello world");
  1. 监听事件

  2. 发出事件

  3. 事件队列

思路

实现一个对象,监听方法on将事件加入到队列中,触发方法emit将找到对应的队列中的事件,并触发回调。

对象实现

let Event = {}; //

Object.defineProperty(Event, "_cbQueue", {
  value: {},
  writable: true,
  enumerable: false, //将枚举设置为false,防止在copy属性的时候,不会被复制。
  configurable: true
});

Event.on = function (type, handler) {
  this._cbQueue = this._cbQueue || {};
  this._cbQueue[type] = this._cbQueue[type] || [];
  this._cbQueue[type].push(handler);
  return this;
}

Event.emit = function (type, data) {
  if (this._cbQueue[type]) {
    this._cbQueue[type].forEach(cb => {
      cb(data);
    });
  }else {
    throw new Error('not found custom event : ' + type)
  }
}

Event.off = function (type, handle) {
  var handles = this._cbQueue[type];
  if (handles) {
    if (!handle) {
      this._cbQueue[type] = [];
    } else {
      for (var i = 0; i < handles.length; i++) {
        if (handles[i] === handle) {
          this._cbQueue[type].splice(i, 1);
        }
      }
    }
  }

}
module.exports = Event;

ES6 Class 实现

class Event {
  constructor() {
    this._cbQueue = {};
  }
  on(type, handler) {
    if (!this._cbQueue[type]) {
      this._cbQueue[type] = [handler]
    }else{
    this._cbQueue[type].push(handler)
    }

  }
  emit(type, data) {
    if (this._cbQueue[type]) {
      this._cbQueue[type].forEach(cb => {
        cb(data)
      });
    } else {
      throw new Error('not found custom event : ' + type)
    }
  }
  off(type, handler) {
    const handles = this._cbQueue[type];
    if (handles) {
      if (!handler) {
        this._cbQueue[type] = [];
      } else {
        for (var i = 0; i < handles.length; i++) {
          if (handles[i] === handler) {
            this._cbQueue[type].splice(i, 1);
          }
        }
      }
    }
  }
}

module.exports = Event

同步code地址: https://github.com/webkong/book-codes/tree/master/simpleEventEmitter

Last updated