I am working on a leaderboard using Firebase as backend. They have given this tutorial - https://www.firebase.com/tutorial/#session/e5u73mr8wvp
I want help interpreting the following lines of code and how it keeps the element sorted.
if (prevScoreName === null) {
$("#leaderboardTable").append(newScoreRow);
}
else {
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
The function for handling the 'score added', from where this snippet is taken -
function handleScoreAdded(scoreSnapshot, prevScoreName) {
var newScoreRow = $("<tr/>");
newScoreRow.append($("<td/>").append($("<em/>").text(scoreSnapshot.val().name)));
newScoreRow.append($("<td/>").text(scoreSnapshot.val().score));
// Store a reference to the table row so we can get it again later.
htmlForPath[scoreSnapshot.key()] = newScoreRow;
// Insert the new score in the appropriate place in the table.
if (prevScoreName === null) {
$("#leaderboardTable").append(newScoreRow);
}
else {
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
}
I suggest, for more information, you take a look at the tutorial link given above and please interpret step by step the above code snippet which I posted before this.
Child added, changed, and moved callbacks are passed a second parameter containing the key of the previous child. This is how the code is able to sort the elements.
Each child is sorted on Firebase in ascending order because these children have a priority equal to their score, which is why in the code, the child with no previous child is appended to the bottom. This is done to make the table appear to be sorted in a descending order, as a leaderboard should be.
Here are some better comments to explain what's going on.
if (prevScoreName === null) {
// This child has no child before it, which means it has the lowest score.
// Append it to the bottom of the table.
$("#leaderboardTable").append(newScoreRow);
}
else {
// This child has a child before it with a lower score. Find that previous
// child in the DOM so we can insert the new child above it.
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}