Knockout -根据observableArray检查复选框

Knockout - Checking checkboxes according to observableArray

本文关键字:检查 复选框 observableArray -根 Knockout      更新时间:2023-09-26

所以我有一个时间表列表,我需要为用户显示,并显示他或她目前的时间表,并给他们的可能性跳上和退出说时间表。

我的视图是这样的

self = this;
self.shifts = ko.observableArray();
self.selectedShifts = ko.observableArray();
//I populate self.shifts here with a WEB API call
//Run through each shift and check if current user is on it and set checked / not checked    value for checkbox
        ko.utils.arrayForEach(self.shifts(), function(shift) {
           //Clear array
            self.usersOnShift([]);
            //Populate array with all users on the shift
            self.usersOnShift = ko.observableArray(WEB API CALL HERE);
            var userInShift = ko.utils.arrayFirst(self.usersOnShift(), function(user) {
                if (selectedUserId == user.ID) {
                    return true;
                } 
            });
            if (userInShift) {
                self.selectedShifts.push(shift.ID);
            }
        });
ko.applyBindings(self);

我的HTML是这样的

  <div class="simple_overlay" id="shiftOverlay">
        <div class="details">
            <div data-bind="foreach: shifts">
                <div><span class="staff-initials" data-bind="text:wardName">  </span><input type="checkbox" data-bind="value: ID, checked: $root.selectedShifts"/>  </div>
            </div>
            <div>
                <a href="#" data-bind="click: updateUserOnShifts">Connect</a>
                <a href="#" data-bind="click: closeShiftDialog">Close</a>
            </div>
        </div>
    </div>

我可以看到复选框的值被正确地设置为相应班次的ID。但是,我知道所讨论的用户是on的移位不被检查,我知道selectedShifts observableArray包含值。

"checked: $root。selectedShifts"呼叫/检查不工作,但我知道它包含正确的值。我做错了什么?

问题是您的值是一个整数,但是当绑定到checkbox元素时,它变成了一个字符串。当checked绑定试图在数组中查找值时,它没有找到匹配,因为它使用严格相等进行比较,并且(2 === "2")为false。

解决这个问题的最简单方法是在将值添加到数组中时将其转换为字符串:

self.selectedShifts.push("" + shift.ID);

当然,这意味着你的模型必须改变,这可能不是一个很好的解决方案。我提出了一个自定义绑定checkedInArray,它取代了checked并支持任何类型的值。您可以了解它,查看它的实际操作,并像这样使用它:

<input type="checkbox" data-bind="checkedInArray: {value: ID, array: $root.selectedShifts }" />

在Knockout 2.3.0中(仍在开发中)将有一个新的绑定checkedValue,它将允许您在checked绑定中使用任何类型的值。使用该版本,您可以将HTML更新为使用checkedValue:

<input type="checkbox" data-bind="checkedValue: ID, checked: $root.selectedShifts"/>

是移位。ID一个可观察属性?如果是,那么您需要像这样将其添加到数组中:

self.selectedShifts.push(shift.ID());

否则你只是将整个可观察对象添加到数组中,而不是值。