knockoutjs绑定到主视图模型中所选子视图模型的ko.observableArray

时间:2013-11-29 18:59:11

标签: javascript knockout.js

在knockoutjs中我有一个主视图模型,其中包含一组子视图模型,如下所示

//apply binding on document ready
$( document ).ready(function() {
  ko.applyBindings(new MainviewModel);
});

//main view model, contains a child view models ko.observableArray
var MainviewModel = function()
{
    // ko.observableArray of subviewmodels
    this.subViewModels= ko.observableArray
    ([
        new SubViewModel('A'),
        new SubViewModel('B'),
        new SubViewModel('C')
    ]);

    //selected subviewmodel
    this.selectedSubViewModel = ko.observable();

    //set slected subviewmodel
    this.selectSubViewModel = function(subviewmodel)
    {
        this.selectedSubViewModel = selectedSubViewModel(subviewmodel);
    }
};

    //child view model, contains ko.observableArray of models
var SubViewModel = function(key)    
{ 
    this.key = key;   
    //load items from json based on key value...
    //ko.observableArray of subviewmodels
    this.items=ko.observableArray([new Model("car","4 wheels"), new Model("plane","can fly")]);
    //selected model
    this.selectedModel = ko.observable();
    //set selected model
    this.selectModel = function(item)
    {
        this.selectedModel = selectedModel(item);
    }
};

//model
var Model = function(word,defention)
{
    //properties
    this.word = word;
    this.defention = defention;
};

并且在我的html中我有2个列表更改第一个列表中的选择应该更改第二个列表的源,但是当我更改列表中的选择时没有任何反应,当我在chrome中调试时我得到Uncaught ReferenceError: selectedSubViewModel is not defined < / p>

<!--main view model list view-->
<div class="list-group" data-bind="foreach: subViewModels">
<a href="#" class="list-group-item" data-bind="css: {active: $parent.selectedSubViewModel() == $data}, click: $parent.selectSubViewModel.bind($parent)">
<h4 class="list-group-item-heading" data-bind="text: key"></h4>              
</a>
</div>

<!--selected sub view model list view-->
<div class="list-group" data-bind="foreach: selectedSubViewModel.items">  
     <a href="#" class="list-group-item" data-bind="css: {active: $parent.selectedModel() == $data}, click: $parent.selectModel.bind($parent)">
     <h4 class="list-group-item-heading" data-bind="text: word"></h4>
     <p class="list-group-item-text" data-bind="text: defention"></p>
     </a>
</div>

1 个答案:

答案 0 :(得分:3)

您的主要问题是,您的selectSubViewModelselectModel会不情愿地尝试设置您的selectedSubViewModelselectedModel观察点。

正确的语法是:

this.selectSubViewModel = function(subviewmodel)
{
    this.selectedSubViewModel(subviewmodel);
}

this.selectModel = function(item)
{
    this.selectedModel(item);
}

另见文档:Reading and writing observables

然而,它不会使您的代码生效,因为第一次执行foreach: selectedSubViewModel.items绑定时selectedSubViewModelnull而KO将找不到{{1} }}。

为避免这种情况,您可以使用with binding来包装您的foreach。在这种情况下,只有在selectedSubViewModel.items中有内容且您不必编写selectedSubViewModel时才会呈现第二个列表,只需编写selectedSubViewModel.someproperty等等:

foreach: items

演示JSFiddle