Last active
November 5, 2019 04:58
-
-
Save ccnokes/bb844de2b916350a306d1486b7665e68 to your computer and use it in GitHub Desktop.
A Map class with built-in event emitter that emits a `update` event whenever something changes
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 ObservableMap<K, V> extends Map<K, V> { | |
readonly events = new EventEmitter(); | |
set(key: K, value: V) { | |
let previousValue = this.get(key); | |
super.set(key, value); | |
this.events.emit("update", { | |
key, | |
action: "set", | |
previousValue, | |
currentValue: this.get(key) | |
}); | |
return this; | |
} | |
delete(key: K) { | |
let previousValue = this.get(key); | |
let ret = super.delete(key); | |
this.events.emit("update", { | |
key, | |
action: "delete", | |
previousValue | |
}); | |
return ret; | |
} | |
clear() { | |
this.events.emit("update", { | |
action: "clear" | |
}); | |
super.clear(); | |
return this; | |
} | |
} | |
// test it out .... | |
let map = new ObservableMap<string, number>(); | |
map.events.on("update", console.log); | |
map.set("a", 1); | |
map.set("a", 2); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment