knockoutjs deselect/select all checkboxes when one or more items deselected

蹲街弑〆低调 提交于 2019-12-25 09:36:18

问题


This is similar to, but different from other questions around this topic.

I have a table with a list of records, each having a select checkbox.

In the table header I have a "Select All" checkbox.

When the user checks/unchecks "Select All" the records are selected/unselected. This works fine.

However, I need to deselect my "Select All" checkbox when one or more of the records are deselected.

My markup:

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

My script (edited):

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

回答1:


This works

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

but will give you a ordo n ^ 2 problem when selecting deselecting all, you can use a pasuable computed to get around that

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

edit: You can also extend the computed with a throttle, this way you avoid the ordo n^2 problem

.extend({ throttle: 1 })

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




回答2:


You should make SelectAll computed observable like this:

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

and strip SelectAll.subscribe out.

http://jsfiddle.net/Yqj59/



来源:https://stackoverflow.com/questions/14980066/knockoutjs-deselect-select-all-checkboxes-when-one-or-more-items-deselected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!