knockout templates #1

by RobertSudwarts

HTML

<h2>Employees</h2>
Here are the employees:
<!-- there would/might be a use for mako here -->
<div data-bind="template: { name: 'person-template', data: emp1 }"></div>
<div data-bind="template: { name: 'person-template', data: emp2 }"></div>
<div data-bind="template: { name: 'person-template', data: emp3 }"></div>
<div data-bind="template: { name: 'person-template', data: emp4 }"></div>

<!-- there'd be no need for a foreach using mako -->
<script type="text/html" id="person-template">
    <h4 data-bind="text: name"></h4>
    <p>Credits: <span data-bind="text: credits"></span></p>
</script>

JavaScript

/* So what's going on here?

We have: 
 * a viewModel declaring three employees. Their name & credits
 * a <div> for each template
 * a template which has the html to be displayed
*/
function MyViewModel() {
    var self = this;
    self.emp1 = { name: 'Frank', credits: 250 };
    self.emp2 = { name: 'Bill', credits: 5800 };
    self.emp3 = { name: 'John', credits: 5800 };
    self.emp4 = { name: 'Fred', credits: 600 };
}
ko.applyBindings(new MyViewModel());