Updating table with Dynatable plugin

无人久伴 提交于 2020-01-20 22:54:07

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/20891127/updating-table-with-dynatable-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!