Knockoutjs.com - Templating example

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

by wimpyprogrammer

HTML

<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<div class='liveExample'> 
    
    <h2>1. Basic custom binding</h2>
    <ul data-bind="myforeach: people">
        <li><span data-bind="text: name"></span></li>
    </ul>
    
    <h2>2. Basic custom binding with data attribute</h2>
    <ul data-bind="myforeach: { data: people }">
        <li><span data-bind="text: name"></span></li>
    </ul>
    
    <h2>3. Basic standard binding template</h2>
    <ul data-bind="template: { name: 'person-template', foreach: people }"></ul>
    
    <h2>4. Basic standard binding template with data attribute</h2>
    <ul data-bind="template: { name: 'person-template', foreach: { data: people } }"></ul>
    
    <h2>5. Basic custom binding template</h2>
    <ul data-bind="template: { name: 'person-template', myforeach: people }"></ul>
    
    <h2>6. Basic custom binding template with data attribute</h2>
    <ul data-bind="template: { name: 'person-template', myforeach: { data: people } }"></ul>
</div>

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

CSS

body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample h2 { margin-top: 0.4em; }

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

JavaScript

ko.bindingHandlers.myforeach = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        return ko.bindingHandlers['foreach']['init'](element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        return ko.bindingHandlers['foreach']['update'](element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
    }
};

var Person = function(name) {
    this.name = name;
}
 
var viewModel = {
    people: [
        new Person("Annabelle"),
        new Person("Bertie"),
        new Person("Charles")
        ]
};
 
ko.applyBindings(viewModel);