没有做任何异常处理,简单模拟实现
class E{
__events = {};
constructor(){}
on(type , callback){
if(this.__events[type]){
this.__events[type].push(callback);
return true;
}
else{
this.__events[type] = [callback];
return false;
}
}
emit(type, ...args){
if(this.__events[type] && this.__events[type].length){
this.__events[type].forEach(cb => {
cb.call(this,args);
});
}
}
off(type, callback){
if(this.__events[type] && this.__events[type].length){
this.__events[type] = this.__events[type].filter((cb)=>{
return cb !== callback && cb.ref !== callback;
})
return true;
}
return false;
}
once(type, callback){
let once_func = function(...args){
callback.call(this,...args);
this.off(type,once_func);
}
once_func.ref = callback;
this.on(type,once_func);
}
}
let obj = new E();
function cb (data) { console.log(data);}
obj.on("f1",cb);
obj.off("f1",cb);
obj.emit("f1", 1,2,3,4,5);