Last active
January 16, 2017 21:29
-
-
Save sylvainpolletvillard/d1c3c83a070dc47f11ecf6ef46c71499 to your computer and use it in GitHub Desktop.
EventListener and the quest of the minimal pubsub
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 extends Map { | |
on (e,f){ this.set(e, [...this.get(e)||[], f]) } | |
off(e,f){ this.set(e, (this.get(e)||[]).filter(x => f && x !== f)) } | |
emit(e,...a){ (this.get(e)||[]).map(f => f(...a)) } | |
} | |
// minified classless fit-in-a-tweet version | |
E=(M=new Map,_=e=>M.get(e)||[])=>({on(e,f){M.set(e,[..._(e),f])},off(e,f){M.set(e,_(e).filter(x=>f&&f!==x))},emit(e,a){_(e).map(f=>f(a))}}) | |
// Usage example: | |
var observable = E(); // or new EventEmitter() | |
function log(n){ console.log(n); } | |
observable.on("myEvent", log) | |
observable.emit("myEvent", 1) | |
observable.on("anotherEvent", x => log(2*x)) | |
observable.emit("anotherEvent", 1) | |
observable.on("myEvent", function(){ console.log(3) }) | |
observable.off("myEvent", log); | |
observable.emit("myEvent") | |
observable.off("myEvent"); | |
observable.on("anotherEvent", function(){ console.log(5) }) | |
observable.emit("anotherEvent", 2); | |
// 1 2 3 4 5 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment