码迷,mamicode.com
首页 > 其他好文 > 详细

实现一个eventEmitter

时间:2018-08-16 23:47:07      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:nbsp   listeners   rop   move   bsp   ice   slice   []   this   

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

标签:nbsp   listeners   rop   move   bsp   ice   slice   []   this   

原文地址:https://www.cnblogs.com/dragon-cat/p/9490679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!