Aurelia: reference to calculated values

In my application, I need to have some forms with strings of values ​​that need to be summed. I need to iterate over these lines, having inputs for them, and then build the amount that needs to be updated when editing the inputs.

Here is a simplified example: Class:

export class example { items = [ { id: 1, val: 100 }, { id: 2, val: 200 }, { id: 3, val: 400 } ]; get sum() { let sum = 0; for (let item of this.items) { sum = sum + parseFloat(item.val); } return sum; } } 

View:

 <div repeat.for="item of items" class="form-group"> <label>Item ${$index}</label> <input type="text" value.bind="item.val" class="form-control" style="width: 250px;"> </div> <div class="form-group"> <label>Summe</label> <input type="text" disabled value.one-way="sum" class="form-control" style="width: 250px;" /> </div> 

So far, everything is working as I expect. But: this is a dirty check on sum all the time, and I'm afraid to run into performance issues in a more complex application. So I tried using the @computedFrom decorator, but none of these versions work:

 @computedFrom('items') @computedFrom('items[0]', 'items[1]', 'items[3]') @computedFrom('items[0].val', 'items[1].val', 'items[3].val') 

In all these cases, the sum is calculated only once, but not after editing the values. And the last 2 will not be a good solution, because I may have a change in the number of elements in my model.

Any suggestions on how I can get a computed value that changes when the fields it depends on are changed without checking dirty?

+5
source share
1 answer

use @computedFrom for the val prop element:

 import {computedFrom} from 'aurelia-framework'; export class Item { constructor(id, val, parent) { this.id = id; this._val = val; this.parent = parent; } @computedFrom('_val') get val() { return this._val; } set val(newValue) { this._val = newValue; this.parent.calculateSum(); } } export class Example { sum = 0; items = [ new Item(1, 100, this), new Item(2, 200, this), new Item(3, 400, this) ]; constructor() { this.calculateSum(); } calculateSum() { let sum = 0; for (let item of this.items) { sum = sum + parseFloat(item.val); } this.sum = sum; } } 

For some other ideas, take a look at fooobar.com/questions/384421 / ...

+7
source

All Articles