Datatables.net 1.9.1 & Knockout
This is an example of the integration of Knockout and Datatables.net.
HTML
<script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.js"></script>
<link rel="stylesheet" href="https://raw.github.com/DataTables/DataTables/master/media/css/demo_table_jui.css">
<script src="https://raw.github.com/CogShift/Knockout.Extensions/master/Javascript/src/cog.js"></script>
<script src="https://raw.github.com/CogShift/Knockout.Extensions/master/Javascript/src/cog.utils.js"></script>
<script src="https://raw.github.com/CogShift/Knockout.Extensions/master/Javascript/src/knockout.bindings.dataTables.js"></script>
<link rel="stylesheet" href="http://datatables.net/release-datatables/media/css/demo_table.css" title="http://datatables.net/release-datatables/media/css/demo_table.css">
<script src="http://datatables.net/release-datatables/media/js/jquery.dataTables.min.js"></script>
<div Id="sample2">
<h2>
Gifts</h2>
<p>
You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
<table data-bind="dataTable: { dataSource : gifts, rowTemplate: 'sample2RowTemplate',
options: {
aoColumns: [
{ sTitle: 'Id', mDataProp:'Id' },
{ sTitle: 'Title', mDataProp:'Title' },
{ sTitle: 'Price', mDataProp:'Price' },
{ sTitle:'delete', mDataProp: null, fnRender: function(obj) {
return 'blah'
}
}
]}}" class="display" id="example">
<thead>
</thead>
<tbody>
</tbody>
</table>
<br/>
<label>New Title</label>
<input id="newTitle" type="text" />
<br/>
<label>New Price</label>
<input id="newPrice" type="text" />
<br />
<button data-bind="click: addGift">
Add Gift</button>
<br />
<br /><button data-bind="click:...
JavaScript
var initialData = [{
Id: 1,
Title: 'Star Wars Blue Ray',
Price: '90.00'}];
var initCounter = 1;
//define record class
function GiftRecord(id, title, price) {
this.Id = ko.observable(id);
this.Title = ko.observable(title);
this.Price = ko.observable(price);
}
//map the records
var mappedData = ko.utils.arrayMap(initialData, function(item) {
return new GiftRecord(item.Id, item.Title, item.Price);
});
//Build viewModel
function viewModel() {
this.gifts = ko.observableArray(mappedData);
this.addGift = function() {
initCounter += 1;
var title = $("#newTitle").val();
var price = $("#newPrice").val();
var rec = new GiftRecord(initCounter, title, price);
this.gifts.push({
Id: rec.Id,
Title: rec.Title,
Price: rec.Price
});
};
this.removeGift = function(gift) {
this.gifts.remove(function(item2) {
return gift.Id == item2.Id;
});
};
this.testUpdate = function() {
this.gifts()[0].Title("test123");
};
this.save = function() {
ko.utils.postJson(location.href, {
gifts: ko.toJS(this.gifts()),
guid: giftsSignalR.guid
});
};
}
vm = new viewModel();
//Bind viewModel to HTML
$(function() {
ko.applyBindings(vm, $("#sample2")[0]);
});