3

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.

Anters Bear
  • 1,816
  • 1
  • 15
  • 41
  • Don't use Object.watch like in the duplicate! See this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch for why and what else to use – baao Jul 08 '18 at 08:39

1 Answers1

2

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.

lorefnon
  • 12,875
  • 6
  • 61
  • 93