Saturday, August 10, 2013

Template binding in KnockoutJS

Template binding populates the associated DOM element with the results of a rendering a template. It’s a good way to build UI structures.

    <div data-bind="template: { name:'person-template', data: buyer }">
    </div>

    <script type="text/html" id="person-template">
        <h3 data-bind="text: name"></h3>
    </script>

    <script type="text/javascript">
        var vm = {
            buyer: {
                name: 'Peter'
            },
            seller: {
                name: 'Jason'
            }
        };

        ko.applyBindings(vm);


    </script>

Native templating: underpins foreach, if, with and other control flow bindings. These will capture the HTML markup contained in your element and use it as a template to render against arbitrary data item. This is built into KO.

String based templating: way to connect KO to 3rd party templating engines. KO will pass your model values to external template engine and inject the resulting markup string into document.

Notes:
Avoid combining other bindings with template binding, especially under data-heavy scenarios. Knockout uses one computed observable to track all bindings of an element.

See Ryan's article here

Parameters
Main parameter: Shorthand syntax: if you just supply a string value, KO will interpret this as the ID of a template to render.


For more control, pass a JavaScript object with some combination of the following properties

Rendering a named template
Normally when using control flow bindings, there’s no need to give names to your template. But if you want you can factor out template in to separate element and reference them by name.

Resources
http://www.strathweb.com/2012/08/knockout-js-pro-tips-working-with-templates/
http://aboutcode.net/2012/11/15/twitter-bootstrap-modals-and-knockoutjs.html

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook