Search code examples
data-bindingpolymerpolymer-1.0observerscomputed-properties

Polymer 1.0 wildcard bind against a nested subproperty in an array


Say I have a data object like so:

const o = [
  {name: "A", v: 1, other: 0},
  {name: "B", v: 7, other: 0},
  {name: "C", v: 8, other: 0},
  {name: "D", v: 1, other: 1},
]

I want to be able to define a nested observer like:

_sumOfVs(o.*.v)

This way the observer only updates when the v key in the objects are edited, and not recomputed when name or other are updated. Currently the best I can do is to define the observer as _sumsOfVs(o.*):

_sumsOfVs = obj => obj.base.reduce((p,c) => p+c.v, 0)

Thanks!


Solution

  • It doesn't look like there's a way to observe only specific subproperties off a wildcard (o.*.v), but you could check the change-record's path in the wildcard observer (o.*), filtering out unwanted paths so that the observer exits early if the change-record does not apply to .v.

    _sumOfVs: function(changeRecord) {
      if (changeRecord.path.endsWith('.v')) {
        const sum = changeRecord.base.reduce((p,c) => p + Number(c.v), 0);
        console.log('sum', sum);
      }
    }
    

    codepen