我被困在如何使用 knockoutJS 更新 foreach 模板中的行总和
<div id="timeEntryList" data-bind="foreach: timeEntries">
<table >
<tr>
...
<td> //there are more of this, not included here
<input type="number"
data-bind="value: Days[6].Hours,
event: { change: $root.setDirty }" />
</td>
<td> //this part needs to be updated when the above input is changed
<span data-bind="text: $root.sumRow($data)">
</span>
</td>
那里的最后一个 TD 包含一个 span 元素,它显示 foreach 中为当前项目报告的小时数总和。 它在加载数据时正确显示,但在我编辑元素时保持陈旧。 如何在更改输入框的值时更新此元素?
这是我的精简版 View 模型:
var TimeReportModel = function (init) {
this.timeEntries = ko.observableArray(init.TimeEntries);
//... helper functions
};
TimeEntries 是表示每周报告的小时数的对象。 所以它包含一个天数数组,每一天都有一个小时属性。
最佳答案
根据您要绑定(bind)的内容,您似乎要绑定(bind)到常规函数的结果。如果你想在发生变化时看到更新的值,你需要绑定(bind)到一个可观察对象。在您的 View 模型中将总和计算为可观察值并绑定(bind)到它。
我不知道你的 View 模型是什么样子的,也不知道你在添加什么,但它看起来应该是这样的:
// calculate the sum of the hours for each of the days
self.totalDays = ko.computed(function () {
var sum = 0;
ko.utils.arrayForEach(self.days(), function (day) {
sum += Number(day.hours());
});
return sum;
});
这是一个 fiddle进行演示。
关于javascript - KnockoutJS 更新行总和字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12242708/