Checkbox selectAll/De-selectAll using knockout computed

Checkbox selectAll/De-selectAll using knockout computed

by Keyur Patel

HTML

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

CSS

th { font-weight: bold }

JavaScript

function MasterViewModel() {
    var self = this;

    self.People = ko.observableArray();
    
    // self.SelectAll = ko.observable(false);
    
    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);
            });
        }
    });

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

var my = {};

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

    self.Name = name;
    self.Selected = ko.observable(false);
}

var vm = new MasterViewModel;
vm.People(ko.utils.arrayMap(
    [ 'Antony', 'Bob', 'Cassidy' ],
    function (name) { return new my.Person(name); }
    ));

ko.applyBindings(vm);