xyz
xyz

Reputation: 415

knockout : observable count value depending on a function

Suppose I have an observable array

[{type:'red' , value:1},
{type:'blue' , value:'2'},
{type:'red' , value:3},
{type:'red' , value:4}]

Now I need an observable value which returns the count form array with type == red and this count updated every time on any change in object of the observable array.

Upvotes: 4

Views: 3074

Answers (2)

Chris Dixon
Chris Dixon

Reputation: 9167

You need a computed obervable here, something like this will work (untested):

var yourArray = ko.observableArray([]);

var count = ko.computed(function() {
    var items = ko.utils.arrayFilter(yourArray(), function(item) {
         return item.type == "red";
    });

    return items.length;
});

Upvotes: 5

Richard Dalton
Richard Dalton

Reputation: 35793

You can use ko.computed to do this.

Example viewmodel:

function ViewModel() {
    var self = this;
    self.arrayOfObjects= ko.observableArray( [{type:'red' , value:1},{type:'blue' , value:'2'},{type:'red' , value:3},{type:'red' , value:4}]);

    self.count = ko.computed(function() {
        var redItems = ko.utils.arrayFilter(self.arrayOfObjects(), function(arrayItem) {
             return arrayItem.type == 'red';
        });

        return redItems.length;
    });
}

Anything bound to count will have it's value change as the number of red elements changes:

 <span data-bind="text: count"></span>

Example - http://jsfiddle.net/Wmb47/2/

Upvotes: 5

Related Questions