Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EventEmitter ES6
class EventEmitter{
constructor(selector){
this.cb = new Map();
}
on(e,f){
var cb;
if(!this.cb.has(e))
this.cb.set(e, cb = new Set());
else
cb = this.cb.get(e);
cb.add(f);
console.log(e,f,cb,this.cb);
}
once(e,f){
var off = ()=>{
this.off(e,f);
this.off(e,off);
}
this.on(e,f);
this.on(e,off);
}
off(e,f){
if(!f){
delete this.cb.delete(e);
return;
}
var cb = this.cb.get(e);
if(cb)
cb.delete(f);
}
emit(e,...args){
var cb = this.cb.get(e);
if(!cb)
return;
cb.forEach(f=>f(...args));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.