Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating table with Dynatable plugin

Im trying dynatable and Im running into an issue. I not sure how to update records from different json files.

My html body:

<input type="button" value="items a" id="setToItemsA"><br>
<input type="button" value="items b" id="setToItemsB"><br>
<br><br>
<table id="my-final-table">
    <thead>
        <th>Band</th>
        <th>Song</th>
    </thead>
    <tbody>
    </tbody>
</table>

my script

$(document).ready(function() {
    var json1 = [
                  {
                    "band": "Weezer",
                    "song": "El Scorcho"
                  },
                  {
                    "band": "Chevelle",
                    "song": "Family System"
                  }
                ];

    var json2 = [
                  {
                    "band": "Band1",
                    "song": "Song1"
                  },
                  {
                    "band": "Band2",
                    "song": "Song2"
                  }
                ];

    $('#my-final-table').dynatable({
      dataset: {
        records: json1
      }
    });

    $('#setToItemsA').click(
        function() {
            setToItems(json1);
        });
    $('#setToItemsB').click(
        function() {
            setToItems(json2);
        });

    function setToItems (argument) {
        console.log(argument);
        $('#my-final-table').dynatable({
          dataset: {
            records: argument
          }
        });
    }
});

I tried to unbind the table and redo it with the new dataset but did not work. I honestly dont know. Thanks for your help!

like image 266
LouieV Avatar asked Jan 02 '14 20:01

LouieV


1 Answers

See the relevant discussion in this Github issue. The short version is that you want to update your setToItems function so that it

  1. Replaces the original record-set for the dynatable instance.
  2. Calls the process() function of the dynatable instance.

To do this, let's first cache the dynatable instance object when we first instantiate dynatable (so that we don't have to keep loading it every time the setToItems function is called:

var dynatable = $('#my-final-table').dynatable({
  dataset: {
    records: json1
  }
}).data('dynatable');

Now, let's update our function:

function setToItems (argument) {
  console.log(argument);
  dynatable.settings.dataset.originalRecords = argument;
  dynatable.process();
}

In the above, we can set the originalRecords to whatever JSON collection we want. But dynatable won't update the table in the DOM until we call process(). This allows us to do multiple interactions at once if we want, such as adding some filters, changing the page, adding sorts, etc. all at once without triggering a DOM update for each individual change unless we tell it to.

like image 135
jangosteve Avatar answered Sep 24 '22 19:09

jangosteve