2

I want to be able to sort my models in a collection first by their required flag and then value alphabetically.

Currently my code looks like to this:

var myModel = Backbone.Model.extend({
    defaults: {
        required: true,
        value: '',
        ...
    }
};

var myCollection = Backbone.Collection.extend({
    model: myModel,
    comparator: function (model) {
        return -model.get('required');
    }
});

myCollection.create([
     {value: 'A', required: false},
     {value: 'B', required: true},
     {value: 'C', required: false},
     {value: 'D', required: false},
     {value: 'E', required: true}
]);

The comparator sorts my models by required first but I'm at a loss as to how to also sort them alphabetically. Currently when the view renders them they come out

E, B, D, C, A

I want them to be rendered:

B, E, A, C, D

JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
  • possible duplicate of [Javascript, how do you sort an array on multiple columns?](http://stackoverflow.com/questions/2784230/javascript-how-do-you-sort-an-array-on-multiple-columns) – Brad Christie Dec 08 '11 at 15:21
  • 1
    I've answered another question about Backbone and it's "comparator" architecture, which clearly is mis-named since it makes no comparison, and I think it's a real design flaw. – Pointy Dec 08 '11 at 15:25
  • The problem is that I'm not sure how to compare two items the `comparator` doesn't (seem to) give me two objects to compare, just the one. – JaredMcAteer Dec 08 '11 at 15:26
  • I agree - you have to build a fake sort key. See my answer :-) – Pointy Dec 08 '11 at 15:29

1 Answers1

4

Your "comparator" can return a string consisting of the value and a stringified version of your boolean "required" property that'll order things the way you want:

comparator: function(model) {
  return (model.required ? "0" : "1") + model.value;
}

That way, value "A" is compared as "0A" or "1A" depending on the "required" flag.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Edit You fixed your answer so I removed the first part of this comment. Ps. what's the link to your answer discussing the `comparator` architecture, I'd like to read that. edit: – JaredMcAteer Dec 08 '11 at 15:32
  • Oh I didn't pontificate or anything; I just thought it was weird the first time I saw it and now I've been reminded. For example, consider sorting strings in reverse order. How would you concoct a "negative" version of a string? – Pointy Dec 08 '11 at 15:37
  • [Here](http://stackoverflow.com/questions/5013819/reverse-sort-order-with-backbone-js) is a Stackoverflow question (not involving me) that illustrates the issue. – Pointy Dec 08 '11 at 15:39