Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access size of 'foreach:' binding in knockout js >

In this doc : http://knockoutjs.com/documentation/foreach-binding.html iteration is achieved using the 'foreach' binding :

<tbody data-bind="foreach: people">

Is it possible to access the size of this binding via javascript/jquery ?

Something like : alert('People size is '+people.size);

I need to access the size in order to do a simple validation check.

like image 907
blue-sky Avatar asked Mar 07 '13 13:03

blue-sky


1 Answers

Do you mean within the foreach itself? You can call the parent in the loop, then access the observable array again:

$parent.people().length

Or anywhere you have bound your view model, you can call:

people().length

Or you can add a computed observable to your view model. Inside your view model code, assign this to a var named self, then:

var peopleCount = ko.computed(function()
{
    return self.people().length;
}
like image 104
Paul Manzotti Avatar answered Sep 22 '22 06:09

Paul Manzotti