Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active November 5, 2019 04:58
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 ccnokes/bb844de2b916350a306d1486b7665e68 to your computer and use it in GitHub Desktop.
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
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