KnockoutJS Template

by magikMaker

HTML

<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/knockout-latest.debug.js"></script>
<div data-bind="text: description">
</div>

<table data-bind="template: 'rowsTmpl'"></table>

<script id="rowsTmpl" type="text/html">
    <tbody data-bind="template: { name: 'rowTmpl', foreach: rows }"></tbody>
</script>

<script id="rowTmpl" type="text/html">
    <tr data-bind="template: { name: 'cellTmpl', foreach: cells }">
        <td>static</td>
    </tr>
</script>

<script id="cellTmpl" type="text/html">
    <td>
        ${counter}
        <a href="javascript: void(0);" data-bind="text: name"></a> 
    </td>
</script>

CSS

div { height: 20px; }
table { border: black solid 1px; }
td, th { padding: 1px; text-align: center; }

JavaScript

function Cell(name, x, y) {
    this.name = name;
    this.x = x;
    this.y = y;
    this.showDetails = ko.observable(false);
    this.toggleShowDetails = function() {
        this.showDetails(!this.showDetails());
    }.bind(this);
}

Cell.prototype.toString = function() {
    return "(" + this.x + "," + this.y + ")";
}

var viewModel = {
    counter: 0,
    rows: ko.observableArray([]),
    setDescription: function(header) {
        viewModel.description(header.description);
    },
    clearDescription: function() {
        viewModel.description("");
    },
    description: ko.observable("")
};

//setup a 20x20 grid of cells
for (var i = 0; i < 15; i++) {
    
    var row = {
        name: i,
        cells: []
    };
    
    for (var j = 0; j < 15; j++) {
        row.cells.push(new Cell(viewModel.counter++, i, j));
    }
    
    viewModel.rows.push(row);
}

ko.applyBindings(viewModel);