datatables custom binding - with buttons
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css">
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.debug.js"></script>
<table class="table table-condensed" data-bind="dataTable:
{
dataSource: Collection,
rowTemplate: 'rowTemplate',
iDisplayLength: 20,
sPaginationType: 'bootstrap',
gridId: 'tblRequests',
fnDrawCallback: 'bla',
sDom: 't<\'row\'<\'span12\'i><\'span12 paginateRight\'p>>',
columns: [
{'name':'Name' }
]}">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script Id="rowTemplate" type="text/html">
<td data-bind="text: Name"></td>
<td>
<button class="btn btn-mini btn-primary" type="button" data-bind="click: $parent.AddToCart, enable: !$parent.InBasket($data)">Add</button>
</td>
</script>
Items in Cart:<span data-bind="text: Cart().length"></span>
CSS
div.dataTables_info {
padding-top: 8px;
}
div.dataTables_paginate {
float: right;
text-align: right;
margin: 0;
width: 460px;
}
div.dataTables_filter {
text-align: right;
}
table {
margin-bottom: 6px !important;
clear: both;
}
JavaScript
ko.bindingHandlers.dataTable = {
'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if ($.data(element, isInitialisedKey) === true) return;
var binding = ko.utils.unwrapObservable(valueAccessor());
var isInitialisedKey = "ko.bindingHandlers.dataTable.isInitialised";
var options = {};
// ** Initialise the DataTables options object with the data-bind settings **
// Clone the options object found in the data bindings. This object will form the base for the DataTable initialisation object.
if (binding.options) options = $.extend(options, binding.options);
// Define the tables columns.
if (binding.columns && binding.columns.length) {
options.aoColumns = [];
ko.utils.arrayForEach(binding.columns, function(col) {
options.aoColumns.push({
mDataProp: col
});
})
}
// Define column data attributes
if (binding.columns && binding.columns.length) {
options.aoColumns = [];
ko.utils.arrayForEach(binding.columns, function(col) {
options.aoColumns.push({
mDataProp: col.name
});
theIndex = binding.columns.indexOf(col);
if (col.dataSort) {
options.aoColumns[theIndex].iDataSort = col.dataSort;
}
if (col.sortType) {
options.aoColumns[theIndex].sType = col.sortType;
}
if (col.sortable == false) {
options.aoColumns[theIndex].bSortable = col.sortable;
}
if (col.visible == false) {
options.aoColumns[theIndex].bVisible = col.visible;
}
})
}
if (binding.sortingFixed && binding.sortingFixed.length) {
...