BlakeWilliams
BlakeWilliams

Reputation: 940

Backbone complex sort issues

I want to sort a collection by two attributes, one is "complete", which returns true or false, and the second is by id, except I need that one to be in descending. Is there a way to do this?

Upvotes: 0

Views: 342

Answers (1)

mu is too short
mu is too short

Reputation: 434695

Yes, you can do that sort of thing. A collection's comparator takes a one argument or two argument function:

Comparator function can be defined as either a sortBy (pass a function that takes a single argument), or as a sort (pass a comparator function that expects two arguments).

You would want to use the two-argument form, something like this:

comparator: function(a, b) {
    var ac = a.get('complete');
    var bc = b.get('complete');
    if(ac && !bc)
        return 1;
    if(!ac && bc)
        return -1;

    var as = a.get('seconds');
    var bs = b.get('seconds');
    if(as > bs)
        return -1;
    if(bs < as)
        return 1;

    return 0;
}

If you have an older version of Backbone that doesn't understand the two-argument comparator function then you'll have to upgrade or figure out a way to mash complete and seconds together into a single sort key that will sort properly with Underscore's sortBy.

Upvotes: 2

Related Questions