knockoutjs在取消选择一个或多个项目时取消选择/选择所有复选框

Waz*_*ose 0 javascript checkbox selectall knockout.js

这与本主题的其他问题类似,但不同.

我有一个包含记录列表的表,每个记录都有一个选择复选框.

在表格标题中,我有一个"全选"复选框.

当用户选中/取消选中"全选"时,将选择/取消选择记录.这很好用.

但是,当取消选择一个或多个记录时,我需要取消选中"全选"复选框.

我的加价:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th><input type="checkbox" data-bind="checked: SelectAll" /></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: Selected" /></td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

我的脚本(已编辑):

function MasterViewModel() {
    var self = this;

    self.People = ko.observableArray();
    self.SelectAll = ko.observable(false);

    self.SelectAll.subscribe(function (newValue) {
        ko.utils.arrayForEach(self.People(), function (person) {
            person.Selected(newValue);
        });
    });
}


my.Person = function (name, selected) {
    var self = this;

    self.Name = name;
    self.Selected = ko.observable(false);
}
Run Code Online (Sandbox Code Playgroud)

And*_*ers 6

这有效

http://jsfiddle.net/AneL9/

self.SelectAll = ko.computed({
    read: function() {
        var item = ko.utils.arrayFirst(self.People(), function(item) {
            return !item.Selected();
        });
        return item == null;           
    },
    write: function(value) {
        ko.utils.arrayForEach(self.People(), function (person) {
            person.Selected(value);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

但是在选择取消全部时会给你一个ordo n ^ 2问题,你可以使用一个可用的计算器绕过那个

http://www.knockmeout.net/2011/04/pausing-notifications-in-knockoutjs.html

编辑:你也可以用节流扩展计算,这样你就避免了ordo n ^ 2问题

.extend({ throttle: 1 })
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/AneL9/44/