Skip to content Skip to sidebar Skip to footer

Knockoutjs Deselect/select All Checkboxes When One Or More Items Deselected

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

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

Solution 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()) returnfalse;
        returntrue;
    },
    write: function(value) {
        ko.utils.arrayForEach(self.People(), function(person){
            person.Selected(value);
        });
    }
});

and strip SelectAll.subscribe out.

http://jsfiddle.net/Yqj59/

Post a Comment for "Knockoutjs Deselect/select All Checkboxes When One Or More Items Deselected"