forked from cadence/Carbon
48 lines
762 B
JavaScript
48 lines
762 B
JavaScript
|
import {Subscribable} from "./Subscribable.js"
|
||
|
|
||
|
class SubscribeValue extends Subscribable {
|
||
|
constructor() {
|
||
|
super()
|
||
|
this.hasData = false
|
||
|
this.data = null
|
||
|
}
|
||
|
|
||
|
exists() {
|
||
|
return this.hasData
|
||
|
}
|
||
|
|
||
|
value() {
|
||
|
if (this.hasData) return this.data
|
||
|
else return null
|
||
|
}
|
||
|
|
||
|
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
|
||
|
}
|
||
|
|
||
|
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")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
delete() {
|
||
|
this.hasData = false
|
||
|
this.broadcast("removeSelf")
|
||
|
return this
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export {SubscribeValue}
|