Item sample with jQuery UI dialog
by mac2000
HTML
<script src="http://knockoutjs.com/js/jquery.tmpl.js"></script>
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tbody data-bind="template: { name: 'rowTmpl', foreach: items }"></tbody>
</table>
<a href="#" data-bind="click: addItem">Add Item</a>
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: price"></td>
<td>
<a href="#" data-bind="click: function() { viewModel.editItem($data); }">Edit</a>
</td>
<td>
<a href="#" data-bind="click: function() { viewModel.removeItem($data); }">Delete</a>
</td>
</tr>
</script>
<div id="editDisplay" style="display:none">
<div data-bind="text: 'ID: ' + editor.id()"></div>
<div>Name: <input data-bind="value: editor.name" /></div>
<div>Price: <input data-bind="value: editor.price" /></div>
</div>
CSS
td, th { padding: 5px; border: 1px solid black; }
JavaScript
function Item(id, name, price) {
return {
id: ko.observable(id),
name: ko.observable(name),
price: ko.observable(price)
}
}
var viewModel = {
items: ko.observableArray([
new Item(1, "one", 5.50),
new Item(2, "two", 7.25),
new Item(3, "three", 4.75)
]),
addItem: function() {
this.items.push(new Item(0, "new", 5.00));
},
removeItem: function(item) {
this.items.remove(item);
},
editor: new Item(),
editItem: function(item) {
viewModel.editor.id(item.id()).name(item.name()).price(item.price());
$('#editDisplay').dialog({
modal: true,
buttons: {
Accept: function() {
$(this).dialog("close");
item.name(viewModel.editor.name()).price(viewModel.editor.price());
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
};
ko.applyBindings(viewModel);