Carbon/src/js/store/SubscribeValue.js

48 lines
762 B
JavaScript
Raw Normal View History

import {Subscribable} from "./Subscribable.js"
2020-10-15 03:43:37 +00:00
class SubscribeValue extends Subscribable {
constructor() {
super()
this.hasData = false
this.data = null
}
2020-10-15 03:43:37 +00:00
exists() {
return this.hasData
}
2020-10-15 03:43:37 +00:00
value() {
if (this.hasData) return this.data
else return null
}
2020-10-15 03:43:37 +00:00
set(data) {
const exists = this.exists()
this.data = data
this.hasData = true
if (exists) {
this.broadcast("editSelf", this.data)
} else {
this.broadcast("addSelf", this.data)
}
return this
}
2020-10-15 03:43:37 +00:00
edit(f) {
if (this.exists()) {
f(this.data)
this.set(this.data)
} else {
throw new Error("Tried to edit a SubscribeValue that had no value")
}
}
2020-10-15 03:43:37 +00:00
delete() {
this.hasData = false
this.broadcast("removeSelf")
return this
}
2020-10-15 03:43:37 +00:00
}
export {SubscribeValue}