Reputation: 1643
I have the following structure:
A Shopping List is a list of strings basically, but it's made up of a list of categories with inside each a list of items.
In my foreach
binding where I am displaying the shopping list names I also want to give the count of the number of items that are inside that list.
Basically I want something like this:
<ul id="list-list" data-bind="foreach: ShoppingLists">
<li id="list-title" class="list-title" onclick="changecolor(this)">
<div>
<a style="cursor: pointer" data-bind="click: $parent.ShowList">
<span data-bind="text: Description" style="font-size: 16px; color: #252525; font-weight:bold; text-decoration: none; padding-left: 4px;"></span>
<div style="float: right; padding-right: 4px;">
<a style="padding-left: 6px; color: black;" data-bind="click: $root.Edit">Edit</a>
<a style="padding-left: 6px; color: black;" data-bind="click: $root.Delete">Delete</a>
</div>
<div>
<span style="padding-left: 6px; color: black;">Items in list: </span>
<span style="padding-left: 6px; color: black;" data-bind="text: $root.Count()"></span>
</div>
</a>
</div>
</li>
</ul>
With this JavaScript:
Count: ko.computed(function(list){
var val = 0;
for(i = 0; i < $this.Categories.length; i++)
val += $this.Categories[i].ListItems.length
return val;
}, this)
However, I can't figure out how to calculate this value properly.
Upvotes: 0
Views: 143
Reputation: 817
Assuming your list is observable...
this.List = observableArray();
Your List object could contain your string and an observableArray of Categories:
this.Categories = observableArray();
Your Category object could contain a list of Items:
this.Items = observableArray();
You can do something like this on the Category object...
this.Count = ko.computed(function()
{
return this.Items().Length;
}, this);
That should get you a list item count for each category.
Upvotes: 1