0

說我有等的數據對象,以便:聚合物針對陣列中的嵌套子屬性1.0配綁定

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}, 
] 

我希望能夠定義像嵌套觀察者:

_sumOfVs(o.*.v) 

這隻有當對象中的v鍵被編輯時觀察者纔會更新,並且當更新nameother時不會重新計算。目前我能做的最好的是定義觀察者_sumsOfVs(o.*)

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

謝謝!

回答

1

它看起來並不像有觀察只有特定的子屬性過一個通配符(o.*.v)的方式,但你可以檢查變化記錄的路徑通配符觀察者(o.*),過濾掉不必要的路徑,從而觀察者如果更改記錄不適用於.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