简体   繁体   中英

Adding and removing items from a dataTables source array in javascript

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"}
    ]

});

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM