Knockout Data Bindings and Templates Example

In this blog, I will continue with the discussion of data bindings in knockout. We will explore a bit of knockout templating as well.
As usual, let's take a look at the code first:

The "Simple Div Template" is an example of how we can define a template in a div itself. For this, we use the word template as the data-bind item. We need to provide a name for the template. Then we need to define the template with the same id as name. Since we don't want the template definition div to be visible we set the display style to none.
The "Simple Script Template" is a similar example. The only difference here is that instead of div we use a script tag to define the template. 
The "template with foreach binding" shows how we can combine templating and data binding. Here we define a template named st3 to be used for each country. The st3 template simply emits a row with red and blue borders for each row.
The "template with if binding" shows how we can use the if construct to make decisions to show templates. Here, if the showCountries value is true, we show the div for countries.
The "template with 'with' binding" is used to set the data context for the template. In this example, if we had not used the "with:player" data binding, in the internal spans we would have to use player().lastName and player().firstName. If this was a complex template, we would have to type this alot. In such cases with binding comes handy.
The "binding data context" example also shows how we can use some other data contexts if we are inside a data context. Here we can utilize the $parent and $root.  $root in this example is the view model.
The "inline templates" shows how we can define simple templates inline. In this example because of foreach binding, knockout will automatically apply the span to each of the countries.
The "dynamic template selection" shows how we can use a function for the template name. At the time of render, this function will evaluate which template to use. In this example we are saying that if we select show details, we use the detailsTemplate otherwise we use the summaryTemplate.
The "template parameters" shows how we can use afterRender and afterAdd events as part of templating framework. Anytime a dom element is added afterAdd gets fired.