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,執(zhí)行的時候會觸發(fā)fn函數(shù)
callback();//fn函數(shù)中調(diào)用原有的callback
this.removeListener(eventName,fn);//刪除fn,再次執(zhí)行時只會執(zhí)行一次
};
this.on(eventName,fn);//1,先綁定,callback調(diào)用后再解綁,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('失戀');
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。