Datatables.net & Knockout
This is an example of the integration of Knockout and Datatables.net.
by Shrikrishna Gupta
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://github.com/douglascrockford/JSON-js/blob/master/json2.js" title="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<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>
<script src="https://raw.github.com/CogShift/Knockout.Extensions/master/Demo/Knockout.Extensions.Demo.Web/Scripts/DataTables-1.8.2/media/js/jquery.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">
<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', fnRender: function(obj) {
return 'blah'
}
}
]}}" class="display" id="example">
<thead>
</thead>
<tbody>
</tbody>
</table>
<label>New Title</label>
<input...
JavaScript
var initialData = [{
Id: 1,
Title: 'Star Wars Blue Ray',
Price: '90.00'}];
var initCounter = 1;
//Build viewModel
function viewModel() {
this.gifts = ko.observableArray(initialData);
this.addGift = function() {
initCounter +=1;
var title = $("#newTitle").val();
var price = $("#newPrice").val();
this.gifts.push({
Id: initCounter ,
Title: title,
Price: parseInt(price)
});
};
this.removeGift = function(gift) {
// alert(gift);
// this.gifts.remove(gift);
this.gifts.remove(function(item2) {
return gift.Id == item2.Id;
});
};
}
vm = new viewModel();
//Bind viewModel to HTML
$(function() {
ko.applyBindings(vm, $("#sample2")[0]);
});