在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>
答案 0 :(得分:3)
您的主要问题是,您的selectSubViewModel
和selectModel
会不情愿地尝试设置您的selectedSubViewModel
和selectedModel
观察点。
正确的语法是:
this.selectSubViewModel = function(subviewmodel)
{
this.selectedSubViewModel(subviewmodel);
}
this.selectModel = function(item)
{
this.selectedModel(item);
}
另见文档:Reading and writing observables
然而,它不会使您的代码生效,因为第一次执行foreach: selectedSubViewModel.items
绑定时selectedSubViewModel
将null
而KO将找不到{{1} }}。
为避免这种情况,您可以使用with
binding来包装您的foreach。在这种情况下,只有在selectedSubViewModel.items
中有内容且您不必编写selectedSubViewModel
时才会呈现第二个列表,只需编写selectedSubViewModel.someproperty
等等:
foreach: items
演示JSFiddle。