Venkat
Venkat

Reputation: 855

Knockout array filter and Computed observable not working

i am new to Knockout. I am trying out a scenario and i am not able to make it work. please help. I am using 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);

I have binded the IsSelected property to checkbox. Initially the IsSelected property will be set to false.

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

I am always getting the Span value as 0 even if i select the checkbox. But i could see the Property IsSelected changed to true.

Upvotes: 2

Views: 1748

Answers (1)

Anders
Anders

Reputation: 17564

You need to make the IsSelected into a observable for the computed observable to be able to be notified when the value of IsSelected has changed

If it already is a observable then you need to change the code to

return item.IsSelected() == true;

Upvotes: 2

Related Questions