使用knockout选择All复选框

时间:2014-09-03 09:07:13

标签: javascript knockout.js

我正在尝试使用knockout选择所有复选框。这是我的viewmodel

function MasterViewModel() {
var self = this;
self.People = ko.observableArray([new Person("Test1", false), new Person("Test2", false)]);
self.selectedAllBox = ko.observable(false);

self.selectedAllBox.subscribe(function (newValue) {
    if (newValue == true) {
        ko.utils.arrayForEach(self.People(), function (item) {
            item.sel = true;
        });
    } else {
        ko.utils.arrayForEach(self.People(), function (item) {
            item.sel = false;

        });
    }
});

 }
Person = function (name, sel) {
this.Name = name;
this.sel = sel;
}

ko.applyBindings(new MasterViewModel());

这是我的观点

<table>
<thead>
    <tr>
        <th>Name</th>
        <th>
            <input type="checkbox" data-bind="checked: selectedAllBox" />
        </th>
    </tr>
</thead>
<tbody data-bind="foreach: $data.People">
    <tr>
        <td data-bind="text: Name"></td>
        <td class="center">
            <input type="checkbox" data-bind="checked: sel" />
        </td>
    </tr>
</tbody></table>

我无法检查所有内容。这是我的Fiddle。你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:2)

您需要在sel

中观察Person属性
Person = function (name, sel) {
    this.Name = name;
    this.sel = ko.observable(sel);
}

你需要在selectedAllBox.subscribe

中设置这个observable
self.selectedAllBox.subscribe(function (newValue) {
    if (newValue == true) {
        ko.utils.arrayForEach(self.People(), function (item) {
            item.sel(true);
        });
    } else {
        ko.utils.arrayForEach(self.People(), function (item) {
            item.sel(false);

        });
    }
});

演示JSFiddle