Alvaro
Alvaro

Reputation: 41595

Multiple view models break knockout.js

I'm trying to use multiple view models as suggested in the documentation and in this other answer.

I'm getting an error in the console complaining about a variable not being defined:

Uncaught ReferenceError: Unable to process binding "foreach: function (){return seals }" Message: seals is not defined

Reproduction online

HTML

<!-- ko foreach: seals -->
<div class="form-group">
    <label for="seal" class="col-xs-2 control-label" data-bind="text: 'Seal ' + name"></label>
    <div class="col-xs-8">
        <input type="text" class="form-control" data-bind="attr: {name: 'seal' + formName}" />
    </div>
</div>
<!-- /ko -->

JS

ko.applyBindings(demo, document.body);
ko.applyBindings(addEquipmentModel, document.getElementById('whatever'));

Upvotes: 1

Views: 59

Answers (2)

connexo
connexo

Reputation: 56754

If you need several viewmodels nested in your view, or even in a child-parent relation, you should consider using Knockout components for that. Another possibility aside from that is to use apply(this) in your main viewmodel to the other viewmodels 'class' so your main viewmodel sort of inherits the functionality and properties of the referred model. This will, though, lead to problems if you have name concurrencies in your viewmodels.

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

The problem is here:

ko.applyBindings(demo, document.body);

You are applying a model to document.body, so it's going to try and parse and bind the whole document. When it gets to the part with:

<!-- ko foreach: seals -->

You get an error because the demo model doesn't have a seals property.

In practice, you don't want the elements that you are binding to overlap. In other words, don't bind one model to a child element of an element that is bound to another model. They should be siblings, or cousins. Not direct descendants.

Upvotes: 2

Related Questions