Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Created November 4, 2015 07:27
Show Gist options
  • Save dead-claudia/c47be8b2b6907b50d657 to your computer and use it in GitHub Desktop.
Save dead-claudia/c47be8b2b6907b50d657 to your computer and use it in GitHub Desktop.
Observable Map
export default class ObservableMap extends Map {
constructor(...args) {
super(...args)
this._onSet = new Set()
this._onDelete = new Set()
this._onClear = new Set()
}
onSet(f) {
this._onSet.add(f)
return this
}
offSet(f) {
this._onSet.delete(f)
return this
}
onDelete(f) {
this._onDelete.add(f)
return this
}
offDelete(f) {
this._onDelete.delete(f)
return this
}
onClear(f) {
this._onClear.add(f)
return this
}
offClear(f) {
this._onClear.delete(f)
return this
}
set(key, value) {
super.set(key, value)
this._onSet.forEach(f => f(key, value))
return this
}
delete(key) {
super.delete(key)
this._onDelete.forEach(f => f(key))
return this
}
clear() {
super.clear()
this._onClear.forEach(f => f())
return this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment