Template binding
Objective
Template binding uses templates to render data to a page. Template bindings are very handy for building nested structures of pages. By default, Knockout is using the popular Jquery.tmpl template engine. With it, you need to download and reference the Jquery.tmpl and jquery frameworks on the installation page. Or you can integrate other template engines (although you need to know knockout internal knowledge).
Example
<div data-bind='Template: "Persontemplate"'> </div><script id='persontemplate'Type='text/html'>${Name} is${Age} years old<button data-bind='Click:makeolder'>make older</button></script> <script type='Text/javascript'>varViewModel ={name:ko.observable ('Bert'), age:ko.observable ( +), Makeolder:function () { This. Age ( This. Age () +1); } }; Ko.applybindings (ViewModel);</script>
When the referenced observable (dependent observable) data changes, knockout automatically re-render the template. In this example, the template will be re-render each time the button is clicked.
Grammar
You can use any syntax supported by your template engine. Jquery.tmpl performs the following syntax:
${somevalue}-Reference documentation
{{{HTML somevalue}}-Reference document
{{If somecondition}}-reference document
{{Else somecondition}}-reference document
{{Each somearray}}-reference document
Use {{each}} with the observable array
When using {{each somearray}}, of course, if your value is observablearray, you must use the JavaScript type's underlying array type {{each myobservablearray ()}}, Instead of {{each myobservablearray}}.
Parameters
Main parameters
Fast Grammar Memory: If you declare just a string (the last example), KO uses the template's ID to render. The data that is applied to the template is your entire view model object (for example, the Ko.applybindings bound object).
For more controls, you can pass JavaScript objects with the following properties:
Name (required)-template to render ID – reference 5 How to use the function declaration ID.
Data (optional)-you need to render to the template. If you ignore the entire parameter, KO will look for the foreach parameter, or apply the entire view model object.
foreach (optional)-Specify KO in the "foreach" mode of the render template – refer to note 3.
Afteradd or Beforeremove (optional)-Use the callback function in foreach mode.
Templateoptions (optional)-Pass extra data for use when you render the template. Refer to note 6.
Examples of passing multiple parameters:
<div data-bind='Template: {name: ' Persontemplate ', data:someobject}'> </div>
Note 1:render nested templates
Because the Data-bind attribute is used in the template, the nested template can be used again using the data-bind= ' template: ... ' in the elements of the upper template.
This is much more useful than the native syntax caused by the template (for example, {{Tmpl}} in Jquery.tmpl). The advantage of the knockout syntax is that it can be followed by dependent values on each layer of the template, so if the dependency changes, KO will only re-render the template that the dependency is on. This will greatly improve performance.
Note 2:${val} and <span data-bind= ' text:val ' ></span> What is the difference?
When you use the Data-bind property inside a template, Ko is individually tracking dependencies for this binding. When the model changes, KO only updates the bound elements and child elements without having to re-render the entire template. So if you declare that this code is <span data-bind= ' Text:someobservablevalue ' ></span>, when someobservablevalue changes, Ko will simply update the text value of the <span> element without having to re-render the entire template.
However, if the observable value is used internally by the template (for example, ${Someobservablevalue}), if the observable value changes, the KO will render the entire template again.
This means that in many cases <span data-bind= ' Text:someobservablevalue ' ></span> performance is better than ${Someobservablevalue}, Because the value changes, it does not affect the state of the neighboring element. But ${Someobservablevalue} syntax is relatively concise, if your template is relatively small, it is more appropriate, will not bring big performance problems.
Note 3: Using foreach
If you need to render a template for each item in a collection, there are 2 ways:
You can use the native "each" syntax in the template engine to iterate over algebraic groups with {{each}} syntax for Jquery.tmpl.
Another way is to use the knockout foreach mode to render.
Example:
<div data-bind='Template: {name: "Persontemplate", foreach: Someobservablearrayofpeople}'> </div>
The benefits of the foreach template pattern are:
When adding a new item to your collection collection, KO will only render a template for the new item and append the result to the existing DOM.
When the item is deleted from the collection collection, KO will not render any templates again, but simply delete the relevant elements.
Ko allows you to declare Afteradd and Beforeremove's callback functions by customizing the Add/Remove DOM element. The callback will then perform some animations or other actions when deleting the element.
Unlike the native one, the template engine forces a re-render of all the content in the template after the change, because it does not care about the so-called dependency tracking content in Ko.
For an example of using the foreach pattern, refer to Grid editor and animated transitions.
Note 4: Use the AfterRender option
Sometimes you need to define logic in depth on the DOM elements generated by the template. For example, you might want to intercept the template output, and then allow jquery UI commands (such as Date picker,slider, or other) on the render element.
You can use the AfterRender option to simply declare a function (an anonymous function or a function in the view model), and knockout call it back after the render or render template. If you are using foreach, after each item is added to the observable array, knockout immediately calls AfterRender's callback function. For example
<div data-bind='Template: {name: "Persontemplate", data:mydata, AfterRender: Mypostprocessinglogic}'> </div>
Declare a similar function in the view model (for example, the object contains MyData):
Viewmodel.mypostprocessinglogic = function (elements) { // "elements" is an array of DOM nodes J UST rendered by the template // your can add custom post-processing logichere}
Note 5: Dynamically decide which template to use
Sometimes, you might need to decide which template ID to use based on the state of the data. The return ID of the function can be applied to the name selection. If you are using the foreach template pattern, Knockout performs a function (with item as an argument) on each item, thereby returning the value as an ID, otherwise the function accepts the entire data option or the entire view model.
Example:
<ul data-bind='Template: {name:displaymode, foreach: Employees}'> </ul><script type='Text/javascript'>varViewModel ={Employees:ko.observableArray ([{name:"Kari", Active:ko.observable (true)}, {name:"Brynn", Active:ko.observable (false)}, {name:"Nora", Active:ko.observable (false)}]), Displaymode:function (employee) {returnEmployee.active ()?"Active":"Inactive"; //initially "Kari" uses the "active" template, while the others use "inactive" }};//... then later ...Viewmodel.employees () [1].active (true);//Now "Brynn" is also rendered using the "active" template.</script>
If your function refers to a observable value, the value of the binding will change as the value changes. This causes the corresponding template to be re-render.
Note 6: Use Templateoptions to pass additional parameters
If you need to pass in additional data when you bind the template, you can use the Templateoptions object to pass the values. This can help you reuse templates by using some of the filter criteria or characters that are not part of the view model. Another benefit is the use of the range control, which you can refer to through your template to access the data of the Nu Tao.
Example
<ul data-bind='Template: {name: "Persontemplate", foreach: Employees, Templateoptions: {label:"Employee:", Selectedperson:selectedemployee}}'> </ul><script id='persontemplate'Type='text/html'> <div data-bind="CSS: {selected: $data = = = $item. Selectedperson ()"}">${$item. Label} <input data-bind="Value:name"/> </div></script>
Throughout the example, it is possible for persontemplate to use employee and custom objects. By templateoptions we can pass a character label and the currently selected item as Selectedperson to control the style. In the Jquery.tmpl template, these values can be obtained by accessing the properties of the $item object.
Note 7: Templates are pre-compiled and cached
For maximum performance, the knockout embedded template engine Jquery.tmpl uses its own functionality to precompile your template into executable JavaScript code and then caches the output from the compilation process. This will make the template faster and more executable, especially when using a Foreach loop to render the same template.
In general you will not notice this, so often forget. However, when you programmatically rewrite the template <script> element for some reason and the template has been used once before, your change will not bring any changes to the render, because it was precompiled and cached the first time it was used. (If this is a problem, we will consider providing a feature that disables or resets the template cache in the new KO version, but it seems there is no good reason to dynamically change the contents of the template <script> element.)
Note 8: Use a different template engine
If you want to use a different JavaScript template engine (or for some reason you don't want to use dependencies on jquery). We can go to the KO to write a different template engine, for example, in the KO source code jquerytmpltemplateengine.js, although he is to support multiple versions of Jquery.tmpl and compiled. Supporting a single template engine version is relatively straightforward.
Dependence
Template bindings can only work if the appropriate template engine is referenced. For example the Jquery.tmpl engine mentioned.
Fourth Chapter: Template binding