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) {
$.ajax({
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) {
countWatched++;
}
});
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);
userList.remove();
userList.add(values);
}
});
}
}
EDIT 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:
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
Existing
var List = function (id, options, values) {
Changed to
var List = function (id, options, rebuildSort, values) {
Changes to init
Existing
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.
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.