我是 KnockoutJs 的新手,我试图理解错误“无法解析绑定。消息:ReferenceError:未定义项目;绑定值:foreach:项目”推送到 observableArray 时。
下面是 jsFiddle 中的相同代码:http: //jsfiddle.net/TheMetalDog/yYAFJ/
viewModel.items()[0].childItems.push(newItem);
单击“添加子项”按钮时会发生错误。
html:
<div data-bind="template: { name: 'tmpl-item-list' }"></div>
<button type="button" class="add">Add</button>
<button type="button" class="addChild">Add Child</button>
<div class="error"></div>
<script type="text/html" id="tmpl-item-list">
<ul data-bind="foreach: items">
<li>
<span data-bind="text: name"></span>
<div data-bind="template: {foreach: childItems, name: 'tmpl-item-list'}"> </div>
</li>
</ul>
</script>
JS:
var viewModel = {}, i = 5;
viewModel.items = ko.observableArray([]);
viewModel.items.push({name: '1', childItems: ko.observableArray([])});
viewModel.items.push({name: '2', childItems: ko.observableArray([])});
viewModel.items.push({name: '3', childItems: ko.observableArray([])});
viewModel.items.push({name: '4', childItems: ko.observableArray([])});
$('button.add').click(function(){
var newItem = {name: i, childItems: ko.observableArray([])};
viewModel.items.push(newItem);
i++;
});
$('button.addChild').click(function(){
try{
var newItem = {name: i, childItems: ko.observableArray([])};
viewModel.items()[0].childItems.push(newItem);
i++;
}catch(e){
console.log('error', e);
$('.error').append(e.message + '<br />');
}
});
ko.applyBindings(viewModel);