Skip to content

Instantly share code, notes, and snippets.

@yukulele
Created June 22, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukulele/576710cbe81f820dc926 to your computer and use it in GitHub Desktop.
Save yukulele/576710cbe81f820dc926 to your computer and use it in GitHub Desktop.
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