KnockoutJS更新行和字段

KnockoutJS update row sum field

本文关键字:字段 更新 KnockoutJS      更新时间:2023-09-26

我一直在研究如何使用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中当前项目报告的小时数总和。它在加载数据时显示正确,但在编辑元素时保持陈旧。如何在更改输入框的值时更新此元素?

这是我的视图模型在一个非常精简的版本:

var TimeReportModel = function (init) {
    this.timeEntries = ko.observableArray(init.TimeEntries);
    //... helper functions
};

TimeEntries是表示每周报告的小时数的对象。因此,它包含一个天数数组,并且每天都有一个小时属性。

根据您绑定到的内容,您似乎绑定到了一个正则函数的结果。如果您希望看到在发生更改时更新的值,则需要绑定到可观察的值。使总和在视图模型中成为可观察的计算值,并绑定到它。

我不知道你的视图模型是什么样子的,也不知道你在加什么,但它看起来像这样:

// 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;
});

这里有一把小提琴要示范。