T. Frick T. Frick - 7 months ago 15
Javascript Question

How do you properly refresh a list using List.js

I have a reporting page that I don't want page refreshes on. On select list change, I call an API to generate the new report and spit it out to the DOM using List.js. The issue that I'm running into is: only the first report loaded works properly with the sorting functionality. I believe the core of the issue is how I'm 'refreshing' the list. Here is the code:

function initializeReport(videoName) {
if (videoName) {
url: '/api/report/' + videoName,
type: "GET",
dataType: "json",
success: function (data) {
var values = [];
var countWatched = 0;
data.forEach(function (entry) {
values.push({ name: entry.UserName, title: entry.Title, count: entry.Count, time_played: entry.TimePlayed })
if (entry.TimePlayed > 0) {
var options = {
valueNames: ['name', 'title', 'time_played', 'count'],
item: '<li><div class="name"></div><div class="title"></div><div class="time_played"></div><div class="count"></div></li>'
var userList = new List('views', options);

Here is the jsfiddle


After much troubleshooting with this issue, I finally hacked together a solution, but it's not ideal.

Here is the js fiddle to replicate the issue.
To replicate:

  1. Select List 1
  2. Order the list as much as you want.
  3. Select List 2
  4. Order the list by either column once (works).
  5. Order the list by the same column again (does not work).

From the List.js documentation it seems there is no other way of selecting an existing list besides new List("id", options). Therefore, my code creates a new instance of List every time it changes the list's values. This seemed to be the problem. When I dug into the init function in the list.js file, I noticed this line:

self.sort = require('./src/sort')(self);

If you add logging to the './src/sort' functionality you will notice that each time you change the list with the given code then attempt to sort, the sort functionality is called multiplicatively. In essence, every even change of the list is calling the sort functionality an even number of times which will undo itself.

Not having a strong enough javascript background to truly fix this issue, I ended up hacking together a solution. I changed the constructor function for the List. The relevant code is below:

Changes to List signature


        var List = function (id, options, values) {  

Changed to

        var List = function (id, options, rebuildSort, values) {  

Changes to init


                    self.sort = require('./src/sort')(self);  

Changed to

                    if (rebuildSort) {
                        self.sort = require('./src/sort')(self);

From here, you can can tell the constructor if you want to rebuild the sort functionality. I only do this on the first call so the sort functionality is only ever call once. I know this is not the ideal fix, but as I said I don't have the js experience to properly fix this.