0
votes

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

1
if template 1 works why do you want to get template 2 working out of interest? Template 1 that works is the new way of doing it which was introduced in the beta.4imble
It was just out of curiosity. I was wondering if I was doing something incorrectly or it is just a wrong approach. RP Niemayer's answer :'it will not do data-binding or clean up any existing bindings' resolved my doubts.Piotr Skirski

1 Answers

1
votes

When using jQuery templates in Knockout, you will never really want to call .tmpl directly, as it will not do data-binding or clean up any existing bindings.

You would want to use the template binding: http://knockoutjs.com/documentation/template-binding.html.

When you call showBookList you 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).