Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Last active January 16, 2017 21:29
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 sylvainpolletvillard/d1c3c83a070dc47f11ecf6ef46c71499 to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/d1c3c83a070dc47f11ecf6ef46c71499 to your computer and use it in GitHub Desktop.
EventListener and the quest of the minimal pubsub
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