I'm trying to mirror a high scores leader board from my app on a webpage. Following an old raywenderlich tutorial I am using CloudKit JS and Knockout to accomplish this. Naturally, I want to sort by scores from highest to lowest.
The example code in the tutorial uses:
var query = { recordType: 'CD_FinalScore', sortBy: [{ fieldName: 'CD_score'}] };
(Of course, I am plugging in my recordType and fieldName for the example ones.) This did not give me the results I wanted, so I added a sort method on the records fetched by the query:
self.items(records.sort(function(a, b){return b - a}));
This gives me the results I want on Firefox but not on Safari (where the order is the inverse). My gut tells me that I need to focus on the query signature. Can someone tell me what I've done wrong or incompletely? Thanks! For reference, the complete Knockout view model code is here:
function LeaderboardViewModel() {
var self = this;
var container = CloudKit.getDefaultContainer();
var publicDB = container.publicCloudDatabase;
self.items = ko.observableArray();
self.fields = ko.observable('');
self.fields.CD_score = ko.observable('');
self.fields.CD_userName = ko.observable('');
self.fields.CD_submitDate = ko.observable('');
self.fetchRecords = function() {
var query = { recordType: 'CD_FinalScore', sortBy: { fieldName: 'CD_score' } };
// Execute the query.
return publicDB.performQuery(query).then(function(response) {
if(response.hasErrors) {
console.error("response errors: " + response.errors[0]);
return;
}
var records = response.records;
var numberOfRecords = records.length;
if (numberOfRecords === 0) {
console.error('No matching items');
return;
}
//self.items(records); // this is per the original, tutorial
self.items(records.sort(function(a, b){return b - a}));
});
};
container.setUpAuth().then(function(userInfo) {
console.log("setUpAuth");
self.fetchRecords();
});
}
ko.applyBindings(new LeaderboardViewModel());
});
Following the advice from user3297291 (particularly in the link provided), I changed the sort to the following:
And this appears to be working in both browsers (Firefox and Safari).