1

I am using backbone's collection model to display a sorted list of strings on a backbone view. Here is the model and the comparator:

var MenuItems = Backbone.Collection.extend({
  comparator: function (a, b) {
    if (a.get('name') < b.get('name')) {
      return 1;
    } else if (b.get('name') > a.get('name')) {
      return -1;
    }
  },

  model: MenuItem,
  url: '/items'
});

When the code is run, only the first six of the twelve items in the list are sorted, the rest remains unsorted. When comparator: 'name' is used the list is fully sorted, but when a function is used, this problem occurs.

Anyone know why this might be happening? Could this be a Backbone bug? I am using Backbone 1.1.0

Branka
  • 469
  • 1
  • 5
  • 11
  • Could you post the names items that are being sorted? – Divey Jan 21 '14 at 19:00
  • 3
    [""sort" comparator functions take two models, and return -1 if the first model should come before the second, 0 if they are of the same rank and 1 if the first model should come after."](http://backbonejs.org/#Collection-comparator). You're missing one of those three cases so all bets are off. – mu is too short Jan 21 '14 at 19:12
  • @Divey: {Chili con carne,Cheeseburger,Pizza,Caesar salad,Garden salad,Brownie,Carrots,Cheesecake,Green beans,Mashed potatoes,Spaghetti and meatballs,Tomato salad} is being sorted as {Carrots,Tomato salad,Spaghetti and meatballs,Pizza,Mashed potatoes,Green beans,Garden salad,Chili con carne,Cheesecake,Cheeseburger,Caesar salad,Brownie} – Branka Jan 21 '14 at 21:18
  • @mu is too short: adding `else {return 0;}` makes no difference wse – Branka Jan 21 '14 at 21:20

1 Answers1

4

Here is a working code.

var MenuItems = Backbone.Collection.extend({
    comparator: function (a, b) {
        if (a.get('name') < b.get('name')) {
            return -1;
        } else if (a.get('name') > b.get('name')) {
            return 1;
        }
    }
});

Here is jsfiddle with output so you can compare http://jsfiddle.net/ek44Z/2/

The main problem was with function content. You need return -1 in if statement and compare a and b in else if and return 1. Basically your else if have never been called.

Have a good coding.

Eugene Glova
  • 1,543
  • 1
  • 9
  • 12