【问题标题】:knockoutjs deselect/select all checkboxes when one or more items deselected当一个或多个项目被取消选择时,knockoutjs 取消选择/选择所有复选框
【发布时间】:2013-02-20 12:38:56
【问题描述】:

这与围绕该主题的其他问题类似,但又有所不同。

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

在表格标题中,我有一个“全选”复选框。

当用户选中/取消选中“全选”时,记录被选中/取消选中。这很好用。

但是,当取消选择一条或多条记录时,我需要取消选择“全选”复选框。

我的标记:

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

我的脚本(已编辑):

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

【问题讨论】:

    标签: javascript checkbox knockout.js selectall


    【解决方案1】:

    这行得通

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

    但是在选择取消全选时会给你一个 ordo n ^ 2 的问题,你可以使用一个合理的计算来解决这个问题

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

    编辑:您还可以使用节流阀扩展计算,这样可以避免 ordo n^2 问题

    .extend({ throttle: 1 })
    

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

    【讨论】:

    • 那就对了。非常感谢。
    • @Anders 我正在使用没有 Selected 列的 Json 对象绑定数据。通过 Json 对象绑定数据时有什么替代方法?
    • 您需要创建一个 ViewModel,将信息与数据一起保存。
    【解决方案2】:

    您应该像这样使SelectAll 计算可观察:

    self.SelectAll = ko.computed({
        read: function() {
            var persons = self.People();
            for (var i = 0, l = persons.length; i < l; i++)
                if (!persons[i].Selected()) return false;
            return true;
        },
        write: function(value) {
            ko.utils.arrayForEach(self.People(), function(person){
                person.Selected(value);
            });
        }
    });
    

    然后剥离SelectAll.subscribe

    http://jsfiddle.net/Yqj59/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2011-10-09
      • 2021-11-26
      相关资源
      最近更新 更多