Andrew Bailey
Andrew Bailey

Reputation: 31

Multiple ViewModels

I am trying to figure out how to use a master model with sub-models. It is currently just a master-view with a select in it. But I am getting an error in the console. If I had to take a guess on what might be the problem, I would think it would have to do the with the groups data-bind and it not being told which model to bind with.

<select data-bind="foreach: groups, value: selectedOption">
    <option value ="0"></option>
        <optgroup data-bind="attr: {label: label}, foreach: children">
            <option data-bind="text: label, option: value()"></option>
        </optgroup>
</select>
<hr />

<div data-bind="text: specialProperty"></div>
ko.bindingHandlers.option = {
    update: function(element, valueAccessor) {
       var value = ko.utils.unwrapObservable(valueAccessor());
       ko.selectExtensions.writeValue(element, value);   
    }        
};

var mainView = function()
{
    this.ts = new testSelect("B");
}


function testGroup(label, children) {
    this.label = ko.observable(label);
    this.children = ko.observableArray(children);
}

function testOption(label, property) {
    this.label = ko.observable(label);
    this.value = ko.observable(property);
}

var testSelect = function(selectedValue) {
    this.groups = ko.observableArray([
        new Group("Group 1", [
            new Option("Option 1", "A"),
            new Option("Option 2", "B"),
            new Option("Option 3", "C")
        ]),
        new Group("Group 2", [
            new Option("Option 4", "D"),
            new Option("Option 5", "E"),
            new Option("Option 6", "F")
        ])
    ]);

this.selectedOption = ko.observable(selectedValue);
     this.specialProperty = ko.computed(function(){
        var selected = this.selectedOption();
        return selected ? selected : 'unknown';
    }, this);

};
ko.applyBindings(new mainView());

Error

knockout-min.js:72 Uncaught ReferenceError: Unable to process binding "foreach: function (){return new Array(numberOfRows()) }"
    Message: Unable to process binding "foreach: function (){return groups }"
    Message: groups is not defined

here is the jsfiddle: https://jsfiddle.net/gauldivic/bjsswdqu/5/

Upvotes: 0

Views: 55

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

The problem is that your actual model is under the ts property of your view model. You need to reference them through that property.

<select data-bind="foreach: ts.groups, value: ts.selectedOption">
    <option value ="0"></option>
        <optgroup data-bind="attr: {label: label}, foreach: children">
            <option data-bind="text: label, option: value()"></option>
        </optgroup>
</select>
<hr />

<div data-bind="text: ts.specialProperty"></div>

updated fiddle

Upvotes: 1

Related Questions