class EventEmitter{
constructor(){
this.cache = {};
}
on(name,func){
if(this.cache[name]){
this.cache[name].push(func);
}else{
this.cache[name] = [func];
}
}
off(name,func){
let tasks = this.cache[name];
if(tasks){
const index = tasks.findIndex(f =>{
return f === func||f.callback === func;
})
if(index >= 0){
tasks.splice(index,1);
}
}
}
emit(name,once = false,...args){
if(this.cache[name]){
let tasks = this.cache[name].splice();
for(let fn of tasks){
fn(...args);
}
if(once){
delete this.cache[name];
}
}
}
}
console