2

What is eventEmitte

eventEmitter is an object that monitors the event
To put it plainly is to write a callback function for the event,
When an event is triggered,
The callback function bound for the event will be executed.

Node uses an event-driven mechanism, and EventEmitter is the basis for Node to achieve event-driven
Node's events module only provides an EventEmitter class,
This class implements the basic pattern of Node asynchronous event-driven architecture-observer pattern

Manually implement eventEmitte

class EventEmitter{
   constructor(){
      this.handler={};
   }
   on(eventName,callback){
      if(!this.handles[eventName]){
        this.handles[eventName]=[];
      }
      this.handles[eventName].push(callback);
   }
   emit(eventName,...arg){
       if(this.handles[eventName]){
       for(var i=0;i<this.handles[eventName].length;i++){
          this.handles[eventName][i](...arg);
       }
   }
}

调用
let event = new EventEmitter();
event.on('click',function(str){
   console.log(str);
});
event.emit('click','Yeah!');
//输出Yeah!

NANA
94 声望7 粉丝

小魔女