首页 > 其他 > 详细

实现一个eventEmitter

时间:2018-08-16 23:31:41      阅读:251      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!