[英]Aurelia: Binding to computed values
In my application I need to have some forms with rows of values that have to be summed. 在我的应用程序中,我需要有一些表格,其中包含必须求和的值行。 I need to loop through these rows, having inputs for them and then building a sum that should be updated when the inputs are edited.
我需要遍历这些行,为它们提供输入,然后构建一个在编辑输入时应该更新的总和。
Here is a simplified example: The 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;
}
}
The 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>
Until here everything is working like I expect it to do. 直到这里,一切都像我期望的那样工作。 But: it's dirty checking on
sum
all the time and I fear running into performance issues in the more complicated app. 但是:它总是很难检查
sum
,我担心在更复杂的应用程序中遇到性能问题。 So I tried to use the @computedFrom
decorator, but none of these versions works: 所以我尝试使用
@computedFrom
装饰器,但这些版本都@computedFrom
:
@computedFrom('items')
@computedFrom('items[0]', 'items[1]', 'items[3]')
@computedFrom('items[0].val', 'items[1].val', 'items[3].val')
In all of these cases, the sum is just calculated once but not after editing the values. 在所有这些情况下,总和只计算一次,但在编辑值后不计算。 And the last 2 would be no good solution, because I can have a changing amount of items in my model.
最后2个不是很好的解决方案,因为我的模型中可以有不断变化的项目数量。
Any suggestions how I could get a computed value that is changed when fields which it depends on are changed without having the dirty checking? 有什么建议我怎么能得到一个计算值,当它所依赖的字段被更改而没有脏检查?
use @computedFrom
on the item val
prop: 在项目
val
prop上使用@computedFrom
:
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 https://stackoverflow.com/a/32019971/725866 对于其他一些想法,请查看https://stackoverflow.com/a/32019971/725866
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.