Is there an equivalent to didSet from Swift in Javascript? Basicall to call a function automatically when a variable is altered. The purpose of this would be instead of having to call a function each time as follows:
var x = someType()
x.behavior = newBehavior
alterBehavior(x, newBehavior)
function alterBehavior(var,behavior) { // change behavior of var }
I could just do
var x = someType()
someType didSet { // change behavior of var }
x.behavior = newBehavior
This is a trivial example but for my use case this would save me a ton of time / function calls for each sub property everytime it's changed.
Javascript does not have the exact equivalent.
You can simulate something equivalent using proxies which is a lower level API
const target = {
hello: "world",
didSet: (oldVal, newVal) => {
console.log('oldVal =>', oldVal, 'newVal =>', newVal)
}
}
const pseudoTarget = new Proxy(target, {
set(object, prop, val) {
const oldVal = object[prop]
object[prop] = val
if (typeof object.didSet === "function") {
object.didSet(oldVal, val)
}
}
})
Now when you set the property, the didSet function will be called when present.
pseudoTarget.hello = "new world"
VM544:4 oldVal => world newVal => new world
"new world"
For real world projects you may want to use a higher level library like: MobX.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With