I am new to KnockOut JS and I cannot find the reason for data-bind not working in when using jQuery text/x-jquery-tmpl.
Using: jQuery 1.5.2; knockout 1.3.0 beta
I am trying to bind an unordered list to observable array in the view model and bind the checkboxes on list item objects to another ko.observble array with ‘checked’ binding.
The working template code is:
<ul data-bind="foreach: viewModel.booksFromServer()">
<li>
<input type="checkbox" data-bind="checked: viewModel.selectedBooks(), value: Id" />
</li>
</ul>
This does not work, i.e. list is displayed but selected values are not stored in the array:
<script type=""text/x-jquery-tmpl" id="bookTemplate">
{{each data}}
<li>
<input type="checkbox" value="${Id}" data-bind="checked: selectedBooks" />
</li>
{{/each}}
</script>
In the view model I have:
var viewModel ={
selectedBooks = ko.observableArray(),
booksFromServer = ko.observableArray()
//other properties and methods
showBookList: function(bookList){
$("#bookTemplate").tmpl({data: bookList}).appendTo("#book_list");
}
}
What are your thoughts? Thank you in advance for help.
Piotr
When using jQuery templates in Knockout, you will never really want to call
.tmpldirectly, as it will not do data-binding or clean up any existing bindings.You would want to use the
templatebinding: http://knockoutjs.com/documentation/template-binding.html.When you call
showBookListyou can populate an observableArray that is bound using the template binding and your UI will update accordingly. This way your view model is really only ever dealing with data and doesn’t depend on the structure of your UI (no references to jQuery selectors or elements in the view model code).