0

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

2
  • 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. Commented Nov 2, 2011 at 11:16
  • 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. Commented Nov 2, 2011 at 17:24

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your explanation. I am introducing the Knockout framework to an existing project, so I thought that I could just leave large chunks intact and introduce bits of KO when needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.