2012-10-30 92 views
1

我是KnockoutJs的新手,我試圖理解錯誤「無法解析綁定。消息:ReferenceError:項目未定義;綁定值:foreach:項目」一個可觀察的數組。KnockoutJs - 模板中的兒童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); 

回答

2

的問題是,你的模板循環上items並正在從childItems通過模板發送的每個項目。

另一種方法是在最初調用模板時使用foreach而不是在模板內執行items循環。

所以,你原來的結合可能是:

<div> 
    <ul data-bind="template: { name: 'tmpl-item-list', foreach: items }"> 
    </ul> 
</div> 

您的模板看起來像:

<script type="text/html" id="tmpl-item-list"> 
     <li> 
      <span data-bind="text: name"></span> 
      <div data-bind="template: {foreach: childItems, name: 'tmpl-item-list'}"></div> 
     </li> 
</script>​ 

樣品在這裏:http://jsfiddle.net/rniemeyer/yYAFJ/7/