Search code examples
knockout.jsknockout-mapping-plugin

How to use a computed variable to return number of sub items using Knockout and Knockout Mapping Plugin


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.

Js:

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);

Html:

<!-- ko foreach: items -->
  <div>
    <span data-bind="text: title"></span> has <span data-bind="text: viewModel.countSubItems($index)"></span> sub items
  </div>
<!-- /ko -->

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: http://jsbin.com/bonez/1/edit


Solution

  • You will need to wrap your ko.computed into a function and pass that function the itemIndex

    viewModel.countSubItems = function(itemIndex)
    {
      return  ko.computed(function(){       
        return viewModel.items()[itemIndex()].subItems().length;
      });
    };
    

    JSBIN