Created
June 22, 2015 14:24
-
-
Save yukulele/576710cbe81f820dc926 to your computer and use it in GitHub Desktop.
EventEmitter ES6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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