0

これは、このトピックに関する他の質問と似ていますが、異なります。

それぞれに選択チェックボックスがあるレコードのリストを含むテーブルがあります。

テーブル ヘッダーには、[すべて選択] チェックボックスがあります。

ユーザーが「すべて選択」をチェック/チェック解除すると、レコードが選択/選択解除されます。これはうまくいきます。

ただし、1 つ以上のレコードの選択が解除されている場合は、[すべて選択] チェックボックスの選択を解除する必要があります。

私のマークアップ:

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

2 に答える 2

6

これは機能します

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 の問題が発生します。これを回避するには、計算された pasuable を使用できます。

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

編集:スロットルで計算を拡張することもできます。これにより、ordo n ^ 2の問題を回避できます

.extend({ throttle: 1 })

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

于 2013-02-20T13:17:23.753 に答える
1

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/

于 2013-02-20T13:34:03.133 に答える