kendoGrid with KO templates

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.debug.js"></script>
<link rel="stylesheet" href="http://rniemeyer.github.com/knockout-kendo/css/kendo.common.min.css">
<link rel="stylesheet" href="http://rniemeyer.github.com/knockout-kendo/css/kendo.default.min.css">
<script src="http://rniemeyer.github.com/knockout-kendo/js/kendo.all.min.js"></script>
<script src="https://raw.github.com/rniemeyer/knockout-kendo/data-bound-templates/build/knockout-kendo.js"></script>
<div data-bind="kendoGrid: { data: items, columns: [{ title: 'Id' }, { title: 'Name' }, { title: 'Price' }, { title: '' } ], rowTemplate: 'rowTmpl' }"></div>
<button data-bind="click: addItem">Add Item</button>
<script id="rowTmpl" type="text/html">
    <tr>
        <td data-bind="text: id">1</td>
        <td>
            <input data-bind="value: name" />
        </td>
        <td>
            <input data-bind="value: price" />
        </td>
        <td>
            <a href="\#" data-bind="click: $root.removeItem">x</a>         
        </td>
    </tr>
</script>

<hr/>

<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>

JavaScript

var Item = function(id, name, price) {
    this.id = id;
    this.name = ko.observable(name);
    this.price = ko.observable(price);
};

var ViewModel = function() {
    var self = this;
    this.items = ko.observableArray([
        new Item(1, "one", 5),
        new Item(2, "two", 2.75),
        new Item(3, "three", 3)
    ]);
    
    this.count = this.items().length;

    this.addItem = function() {
        self.items.push(new Item(++self.count, "new", 0));
    };
    
    this.removeItem = function(item) {
        self.items.remove(item);
    }
};

ko.applyBindings(new ViewModel());