Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top