Carlos Villalta
Carlos Villalta

Reputation: 107

Sorting Backbone.Collection using date and priority

Ok so, I have a collection filled with objects of a certain model, this model contains a date and a priority, I want it to be sorted by date, then by the priority, I currently have it implemented this way:

App.Collections.Tasks = Backbone.Collection.extend({
model: App.Models.Task,
comparator: function(model) 
{
  return model.get("date") + model.get("priority");
}
});

This is my output:

Get to the party  Edit Delete 1 Fri Feb 1
Get to the party  Edit Delete 2 Mon Jan 28
Go to the store  Edit Delete 4 Mon Jan 28
Go to the mall  Edit Delete 3 Tue Jan 29
Get to the party  Edit Delete 3 Tue Jan 29
Get to the party  Edit Delete 5 Tue Jan 29
Get to the party  Edit Delete 2 Wed Jan 30
Get to work  Edit Delete 5 Wed Jan 30

I want earlier dates to be on top at all times so the february date should be last, how could I achieve this?

Thanks!

Upvotes: 0

Views: 1833

Answers (1)

monshq
monshq

Reputation: 343

You can do it like that:

comparator: function(model1, model2) {
    return (model1.get("date") + model1.get("priority")) -
        (model2.get("date") + model2.get("priority"));
}

Documentation claims, that returned value should be -1, 0 or 1, but that wasn't mandatory earlier and any value could do the trick.

EDIT

comparator: function(model1, model2) {
    var comp = (model1.get("date") + model1.get("priority")) -
        (model2.get("date") + model2.get("priority"));
    if (comp < 0) {
        return -1;
    } else if (comp > 0) {
        return 1;
    } else {
        return 0;
    }
}

Now code precisely follows specification mentioned. If this didn't solve the problem, then the problem is not in comparator.

EDIT

Silly me. I assumed that you are storing a unix time in date, but apparently you don't. Subtracting strings gives NaN, so no sorting is made indeed. So all you need to do now is to cast date to unix time format (or at least something similar), then it should be working.

Upvotes: 1

Related Questions