Search code examples
data-bindingknockout.jsknockout-components

Knockout 3.2 Components - can't access component viewModel root inside foreach binding


Using knockout's new 3.2 Component spec, I'm trying to create a component with a foreach binding inside of it that renders a collection of objects. The objects inside the foreach binding need to have access to attributes on the component's VM, but seem to loose that reference once in the foreach loop.

Is there a simple way to directly access the root of a component's view model inside its template?

Component VM:

function RelatedCompaniesViewModel(params) {
    var self = this;

    self.companies = params.companies;
    self.displayLimit = ko.observable(3);

} 

Component Template:

<!-- ko foreach: companies() -->
    <li data-bind="visible: $index() < displayLimit()">
       ...more bindings...
    </li>
<!-- /ko -->

(returns a "displayLimit is not defined" error)  

Solution

  • Change displayLimit() to $parent.displayLimit().

    Component Template:

    <!-- ko foreach: companies() -->
        <li data-bind="visible: $index() < $parent.displayLimit()">
           ...more bindings...
        </li>
    <!-- /ko -->