Knockout数组过滤器和Computed observable不起作用

时间:2012-11-19 13:39:22

标签: asp.net-mvc knockout.js asp.net-mvc-4

我是Knockout的新手。我正在尝试一个场景,我无法使其工作。请帮忙。我正在使用MVC4。

  function ViewModel(data) {
        var self = this;
        this.Collection = ko.observable(data);


        self.GetFilteredCollection = ko.computed(function () {
            var filteredCollection = ko.utils.arrayFilter(self.Collection(), function (item) {
                return item.IsSelected == true;
            });
            return filteredCollection;
        });

        self.FilteredCollectionCount = ko.computed(function () {
            return self.GetFilteredCollection().length;                
        });
});


var collectionList = eval('<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.Collection) %>');

    var VM = new ViewModel(collectionList);
    ko.applyBindings(VM);

我已将IsSelected属性绑定到复选框。最初,IsSelected属性将设置为false。

<span id="Span1" data-bind="text:$root.FilteredCollectionCount"></span>

即使我选中了复选框,我也总是将Span值设为0。但我可以看到Property IsSelected变为true。

1 个答案:

答案 0 :(得分:2)

当IsSelected的值发生变化时,您需要将IsSelected设置为计算的observable的observable

如果它已经是可观察的,那么您需要将代码更改为

return item.IsSelected() == true;
相关问题