I have bound a KnockOut observableArray to a jQuery DataTable. When I dynamically add items to this array, the new items are correctly being rendered in the table, however some options of the datatable itself are not being refreshed. The pager doesn’t get updated. Also the “no data available” message does not disappear.
HTML:
<table class="table table-striped" id="tblSample">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: List">
<tr>
<td data-bind="text: Name"></td>
</tr>
</tbody>
</table>
<button class="btn" type="button" data-bind="click: AddSample">Test</button>
Knockout model:
var Sample = function(name) {
this.Name = ko.observable(name);
};
var ViewModel = function() {
var self = this;
self.List = ko.observableArray();
self.AddSample = function() {
self.List.push(new Sample('New'));
};
};
ko.applyBindings(new ViewModel());
DOM ready:
$(document).ready(function() {
$('#tblSample').dataTable({
"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"bFilter": true,
"bLengthChange": false,
"bSort": true,
"iDisplayLength": 15,
"oLanguage": {
"sLengthMenu": "_MENU_ records per pagina"
}
});
});
Working JSFiddle: http://jsfiddle.net/PhpDk/1
Am I doing something wrong, or is this a bug?
Thanks,
Nico
(edit: fixed CDN links in jsfiddle)
There is a native knockout grid called KoGrid
https://github.com/ericmbarnard/KoGrid
But if you really want to use Datatables there is a ready to go knockout binding for it (It works with 1.9.0 only)
I have forked that binding on Github and extended it somewhat (You can access Datables object from ViewModel to refresh, filter, sort, etc), you can find it here
https://github.com/AndersMalmgren/Knockout.Extensions