knockoutjs获得符合条件的物品数量

时间:2014-04-14 19:44:03

标签: html knockout.js

我有一个视图模型,里面有一个可观察的数组,里面有一个可观察的数组。当用户从列表中检查项目时,我想跟踪。我有以下视图模型和html:

var mydata = {
        Incomplete: ko.computed(function () {
           // return the count of items that are not IsActive
        }),
        Categories: ko.observable([
              {
                  Description: "Dairy", ListItems: ko.observableArray([
                  { Description: "Eggs", Quantity: "1 Dz.", IsActive: ko.observable(false) },
                   { Description: "Milk", Quantity: "1 Gallon", IsActive: ko.observable(false) }
                  ])
              },
              {
                  Description: "Produce", ListItems: ko.observableArray([
                      { Description: "Lettuce", Quantity: "1 Head", IsActive: ko.observable(false) },
                      { Description: "Oranges", Quantity: "5 ea.", IsActive: ko.observable(false) },
                      { Description: "Greenbeans", Quantity: "1 Thingy", IsActive: ko.observable(false) },
                  ])
              },
        ])
    };

<div data-bind="foreach: Categories" id="list-items">
            <h3 data-bind="text: Description" id="list-heading"></h3>
            <ul data-bind="foreach: ListItems">
                <li>
                    <div class="title">
                        <input type="checkbox" data-bind="checked: IsActive"/>
                        <input type="text" data-bind="value: Quantity, disable: IsActive" class="input-readonly" readonly />
                        <input type="text" data-bind="value: Description, disable: IsActive" class="input-readonly" readonly />
                    </div>
                </li>
            </ul>
        </div>
        <div >
            <span data-bind="text: Incomplete"></span>
            <span >Items left in your list</span>
        </div>

1 个答案:

答案 0 :(得分:5)

使用您当前的代码,您可能希望遍历各个类别,然后遍历各个项目的每个类别循环。这是一个可能的实现:

Incomplete: ko.computed(function () {
    var count = 0;
    ko.utils.arrayForEach(mydata.Categories(), function(category) {
        ko.utils.arrayForEach(category.ListItems(), function(item) {
             if (!item.IsActive()) {
                  count++;
             }
        });
    });

    return count;
}),