let EventEmitter=require('events');
let {inherits}=require('util');
function Girl() {
}
inherits(Girl,EventEmitter);
let girl=new Girl();
girl.on('失恋',cry);
girl.emit('失恋');
function cry() {
console.log('哭')
}
class EventEmitter{
constructor(){
this._events={};
}
on(eventName,callback){
if(!this._events[eventName]){
this._events[eventName]=[callback];
}else {
this._events[eventName].push(callback);
}
}
once(eventName,callback){
let fn=()=>{//绑定的是fn,执行的时候会触发fn函数
callback();//fn函数中调用原有的callback
this.removeListener(eventName,fn);//删除fn,再次执行时只会执行一次
};
this.on(eventName,fn);//1,先绑定,callback调用后再解绑,2要在callback中删除绑定
}
removeListener(eventName,callback){
if(this._events[eventName]){
this._events[eventName]=this._events[eventName].filter(cb=>cb!=callback);
}
}
emit(eventName){
if(this._events[eventName]){
this._events[eventName].forEach(cb=>cb());
}
}
}
let ev=new EventEmitter();
let cry=()=>{console.log('cry')};
ev.once('失恋',cry);
ev.on('失恋',cry);
ev.removeListener('失恋',cry);
ev.emit('失恋');