KnockoutJS–Templates
KnockoutJS–Templates
After being introduced
to KnockoutJS concept and go to know the
basics of data-binding with Observable and
observableArray, let’s move on to how to work with templates and our collection to them.
In this post I’ll explain how to bind a collection with template.
Prerequisites
Now, adding to KnockoutJS Prerequisites (jQuery 1.4.2 and above) you’ll need another Javascript library: jQuery.tmpl . You can download this version or visit the project page for latest version.
HTML as script
The templates are HTML content written inside of a script tag, and it looks like that:
<script type="text/html" id="itemsTemplate">
<!-- Your HTML template content here -->
</script>
The script tag has an ID, it will be used to associate the template to a place in a document where it should be presented
Associate the template
The following HTML element (Unordered list in here) will be associated to the template, as below. the template binding has tow main attributes: name to associate with the template (corresponds to the ID attribute of the template above) and the foreach which corresponds to the observableArray member of the view-model we’d like to bind.
<ul data-bind='template: {name: "itemsTemplate", foreach: rssItems} '>
</ul>
Now, the HTML element is associated with a template and bounded to a data member.
Let’s have a look inside the template:
Binding inside the template
Binding inside the template is very similar to regular binding, only that we bind to and item within a collection instead of binding to a data member inside our view-model.
In order to bind data where there is no suitable type for us (Assign a css class to an input element according to the item’s data) we can use the ($data) expression which points at the whole bounded item and have a JavaScript expression with it, as seen at the example below: (For our XAML friends – let’s say that this is a converter)
<input type="text" data-bind="css:{selectedCustomerClass : ($data) == viewModel.selectedCustomer()}"/>
Summary:
After heaving simple binding we’d like to bind a collection and as we did in every other technology (ASP.Net, WPF, WinForm you name it…) we need a template to bind it to.
Heaving included the template JavaScript library of jQuery.tmpl, we can now write our own templates and bind it to our observableArray .