I’m new to KnockoutJs and am trying to understand the error “Unable to parse bindings. Message: ReferenceError: items is not defined; Bindings value: foreach: items” when pushing to an observableArray.
Here’s the same code below in jsFiddle: http://jsfiddle.net/TheMetalDog/yYAFJ/
The error happens at viewModel.items()[0].childItems.push(newItem); when clicking the, “Add Child” button.
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);
The issue is that your template is looping on
itemsand you are sending each item fromchildItemsthrough that template.An alternative would be to use
foreachwhen you call the template initially and not do theitemsloop inside the template.So, your original binding might look like:
Your template would look like:
Sample here: http://jsfiddle.net/rniemeyer/yYAFJ/7/