美文网首页
nodejs事件模块EventEmitter实现原理

nodejs事件模块EventEmitter实现原理

作者: TerdShow | 来源:发表于2019-10-03 01:30 被阅读0次
function EventEmitter(){
  this._events = Object.create(null);
}

EventEmitter.prototype.on = function(eventName, callback){
  if(!this._events){
    this._events = Object.create(null);
  }
  if(eventName !== 'newListener'){
    this.emit('newListener', callback);
  }
  if(this._events[eventName]){
    this._events[eventName].push(callback);
  }else{
    this._events[eventName] = [callback];
  }
}

EventEmitter.prototype.once = function(eventName, callback){
  let one = ()=>{
    callback();
    this.off(eventName, one);
  }
  one.l = callback;
  this.on(eventName, one);
}

EventEmitter,prototype.off = function(eventName,callback){
  if(this._events[eventName]){
    this._events[eventName].filter(fn=>{
      return fn != callback && fn.l != callback;
    })
  }
}

EventEmitter.prototype.emit = function(eventName, ...args){
  if(this._events[eventName]){
    this._events[eventName].forEach(fn => fn(...args));
  }
}

module.exports = EventEmitter;

相关文章

网友评论

      本文标题:nodejs事件模块EventEmitter实现原理

      本文链接:https://www.haomeiwen.com/subject/fgwqyctx.html