Reputation: 411
I have a DataTables table and I need to use a javascript object as a data source that a user can add and remove items from The DataTables documentation only shows how a fixed array can be used as a data source. The below code doesn't function when an item is added or removed to the array variable. Assume app.array exists and is a Knockout observable array
var files;
$.each(app.array(), function(){
data = "{ \"name\":\"" + this.name.toString() + "\",\"bytes\":\"" + this.bytes.toString() + "\",\"type\":\"" + this.type.toString() + "\"}";
files.push(data);
var table = $("#table").DataTable({
"data": files
, "language":{
"emptyTable": "Nothing is here."
}
, "columnDefs": [
{ targets: [0], visible: true, searchable:false}
]
"columns": [
{"data": "name"}
,{"data": "bytes"}
,{"data": "type"}
]
});
Upvotes: 0
Views: 170
Reputation: 85518
Use destroy: true
and reinitialize each time you have updated the array. Here is a scheme for doing that :
var data = [];
var table;
function render() {
table = $('#example').DataTable({
destroy: true,
data: data,
columns: [
{ data: "name" },
{ data: "bytes" },
{ data: "type" }
]
})
}
render();
var counter = 1;
$('#add').on('click', function() {
data.push({ 'name': counter, 'bytes': counter, 'type': counter })
render();
counter++;
})
demo -> http://jsfiddle.net/y79cwjmy/
Have left out knockout specific peculiarities for clarification. To use an observable array along with dataTables, you could use subscribe
and a second array you pass the observable content to :
var data = ko.observableArray([]);
var dt_data = [];
var table;
function render() {
table = $('#example').DataTable({
destroy: true,
data: dt_data,
columns: [
{ data: "name" },
{ data: "bytes" },
{ data: "type" }
]
})
}
render();
var counter = 1;
$('#add').on('click', function() {
data.push({ 'name': counter, 'bytes': counter, 'type': counter })
counter++;
})
data.subscribe(function(changes) {
dt_data = changes;
render();
});
demo -> http://jsfiddle.net/dkgpb8y6/
Upvotes: 1