Mobx: Introduce support for setters for computed properties

Created on 7 Aug 2016  路  7Comments  路  Source: mobxjs/mobx

馃崡 enhancement

All 7 comments

How would this work? Isn't the point of computed that the data is always derived?

note to self: use actions. @jeffijoe yes, it can't be used to change the computed, but it could be used to change the observable behind the computed, e.g.:

class Distance {

@observable distance = 1

@computed get distanceInMiles() {
  return this.distance * 1.6
}
set distanceInMiles(newValue) {
   this.distance = newValue / 1.6
}

}

@mweststrate that's what I imagine as well - will that example you posted not work today?

That could nicely fit my proposal #421

extendObservable(this, {
  distance: 1,
  distanceInMiles: computed(
    () => this.count * 1.6, // get
    miles => this.distance = miles / 1.6, // set
  )
});

// or:

extendObservable(this, {
  distance: 1,
  distanceInMiles: computed({
    get: () => this.count * 1.6,
    set: miles => this.distance = miles / 1.6,
  })
});

Currently implementing proposal 1 of @andykog 's example. The ES6 variant
will be

class something {
  @observable x = 1
  @computed get y() { 
    return this. x * 2
  }
  set(v) {
    this.x = v / 2
   }
}

See #421 I thin using computed with (extend)Observable should be the idiomatic and promoted approach, but probably it is too breaking to already give a deprecation message for the old approach, maybe in the next minor and then remove it in 3.0

@mweststrate you mean set y(v) { this.x = v / 2 }, right?

Closing, this was released as 2.5.0

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bakedog417 picture bakedog417  路  3Comments

etinif picture etinif  路  3Comments

hellectronic picture hellectronic  路  3Comments

joey-lucky picture joey-lucky  路  3Comments

bichotll picture bichotll  路  3Comments