Knockoutjs.com - Templating example

http://knockoutjs.com/examples/templating.html

by Gonzalo Guevara

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div class='liveExample'> 
    
    <h2>People</h2>
    <ul data-bind="foreach: people">
        <li>
            <div>
                <span data-bind="text: name"> </span> has <span data-bind='text: children().length'>&nbsp;</span> children:
                <a href='#' data-bind='click: addChild '>Add child</a>
                <span class='renderTime' data-bind='visible: $root.showRenderTimes'>
                    (person rendered at <span data-bind='text: new Date().getSeconds()' > </span>)
                </span>
            </div>
            <ul data-bind="foreach: children">
                <li>
                    <span data-bind="text: $data"> </span>
                    <span class='renderTime' data-bind='visible: $root.showRenderTimes'>
                        (child rendered at <span data-bind='text: new Date().getSeconds()' > </span>)
                    </span>
                </li>
            </ul>
        </li>
    </ul>
    <label><input data-bind='checked: showRenderTimes' type='checkbox' /> Show render times</label> <br/>
    <a href='#' data-bind='click: addPerson'>Añadir Persona</a>
    
</div>

CSS

body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }

.renderTime { color: #777; font-style: italic; font-size: 0.8em; }

li { list-style-type: disc; margin-left: 20px; }

JavaScript

// Define a "Person" class that tracks its own name and children, and has a method to add a new child
var Person = function(name, children) {
    this.name = name;
    this.children = ko.observableArray(children);
 
    this.addChild = function() {
        this.children.push("New child");
    }.bind(this);
}
 
// The view model is an abstract description of the state of the UI, but without any knowledge of the UI technology (HTML)
var viewModel = {
    people: ko.observableArray([
        new Person("Annabelle", ["Arnie", "Anders", "Apple"]),
        new Person("Bertie", ["Boutros-Boutros", "Brianna", "Barbie", "Bee-bop"]),
        new Person("Charles", ["Cayenne", "Cleopatra"])
        ]),
    showRenderTimes: ko.observable(false),
    addPerson: function(){
    	this.people.push(new Person('A',[]))
    }
};
 
ko.applyBindings(viewModel);