Pregunta

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);
}
¿Fue útil?

Solución

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/

Otros consejos

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/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top