最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - knockout : observable count value depending on a function - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 1, 2013 at 9:25 Richard Dalton 35.8k6 gold badges74 silver badges92 bronze badges asked May 1, 2013 at 9:06 xyzxyz 4152 gold badges6 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

var yourArray = ko.observableArray([]);

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

    return items.length;
});

You can use ko.puted 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.puted(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/Wmb47/2/

发布评论

评论列表(0)

  1. 暂无评论