Knockout - 根据observableArray检查复选框

时间:2013-03-21 22:32:41

标签: javascript html data-binding checkbox knockout.js

所以我有一个我需要为用户显示的时间表列表,并显示他或她当前所处的时间表,并让他们可以跳过和关闭所述时间表。

我的viewmodel看起来像这样

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。但是,我知道有问题的用户打开了一个班次,我知道selectedShifts observableArray包含该值。

不知何故,“checked:$ root.selectedShifts”调用/检查无效,但我知道它包含正确的值。我究竟做错了什么?

2 个答案:

答案 0 :(得分:10)

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

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

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

当然这意味着你的模型必须改变,这可能不是一个好的解决方案。我想出了一个自定义绑定checkedInArray,它取代checked并支持任何类型的值。您可以learn about itsee it in action,并按照以下方式使用它:

<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"/>

答案 1 :(得分:0)

shift.ID是一个可观察的属性吗?如果是,那么你需要将它添加到数组中:

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

否则你只是将整个observable添加到数组中,而不是值。