实现一个eventEmitter

var eventEmitter = {
  functionList: {},
  oneFunctionList: {},
  on: function (type, fn) {
    if (!Array.isArray(this.functionList[type])) {
      this.functionList[type] = [];
    }
    this.functionList[type].push(fn);
  },
  one: function (type, fn) {
    if (!Array.isArray(this.oneFunctionList[type])) {
      this.oneFunctionList[type] = [];
    }
    this.oneFunctionList[type].push(fn);
  },
  remove: function (type) {
    this.functionList[type] = [];
    this.oneFunctionList[type] = [];
  },
  fire: function (type) {
    if (this.functionList.hasOwnProperty(type)) {
      this.functionList[type].forEach(fn => {
        fn.apply(null, [].slice.call(arguments, 1));
      });
    } else if (this.oneFunctionList.hasOwnProperty(type)) {
      this.oneFunctionList[type].forEach((fn, index) => {
        fn.apply(null, [].slice.call(arguments, 1));
        this.oneFunctionList[type].splice(index, 1);
    } else {
      console.log('no listeners');
    }
  }
}

你可能感兴趣的:(实现一个eventEmitter)