title: How to use a computed variable to return number of sub items using Knockout and Knockout Mapping Plugin
body: <p>I have some data with parent items, along with sub items for each parent. I'm trying to render the count of sub items for each parent, and if a sub item gets removed, the count gets updated.</p>
  
  <p>Js:</p>
  
  <pre><code>var viewModel = ko.mapping.fromJS({
    items: [
      {title: 'red', subItems: [ {subTitle: '1'}, {subTitle: '2'} ] },
      {title: 'blue', subItems: []},
      {title: 'green', subItems: []}
    ]
  });
  
  viewModel.countSubItems = function(itemIndex) {
    return viewModel.items()[itemIndex].subItems().length;
  };
  
  ko.applyBindings(viewModel);
  </code></pre>
  
  <p>Html:</p>
  
  <pre><code>&lt;!-- ko foreach: items --&gt;
    &lt;div&gt;
      &lt;span data-bind="text: title"&gt;&lt;/span&gt; has &lt;span data-bind="text: viewModel.countSubItems($index)"&gt;&lt;/span&gt; sub items
    &lt;/div&gt;
  &lt;!-- /ko --&gt;
  </code></pre>
  
  <p>I'm getting something to the effect of viewModel.items(itemIndex) is undefined. Do I need to combine a function with a computable somehow? Live example (editable) here: <a href="http://jsbin.com/bonez/1/edit" rel="nofollow">http://jsbin.com/bonez/1/edit</a></p>