多个ViewModels

时间:2016-06-17 20:47:43

标签: javascript knockout.js

我试图弄清楚如何使用具有子模型的主模型。它目前只是一个带有选择的主视图。但我在控制台中收到错误。如果我不得不猜测可能存在什么问题,我认为它必须与组数据绑定一起进行,并且不会被告知要绑定哪个模型。

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

错误

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

这里是jsfiddle:https://jsfiddle.net/gauldivic/bjsswdqu/5/

1 个答案:

答案 0 :(得分:1)

问题是您的实际模型位于视图模型的ts属性下。您需要通过该属性引用它们。

<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