Is backbonejs default sort alphabetically with added model to a collection?

148 views Asked by At

Fiddle here http://jsfiddle.net/adamchenwei/966pob6c/

Script Here:

var people = new Backbone.Collection;

people.comparator = function(a, b) {
  return a.get('name') < b.get('name') ? -1 : 1;
};

var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});

people.add(tom);
people.add(rob);
people.add(tim);

console.log(people.indexOf(rob) === 0); // true
console.log(people.indexOf(tim) === 1); // true
console.log(people.indexOf(tom) === 2); // true

I can not comprehend why when these three objects are not index according to its added order but alphabetical? Is there way to disable BB from doing so after a model is added to a collection?

1

There are 1 answers

0
mu is too short On BEST ANSWER

From the fine manual:

comparator collection.comparator

By default there is no comparator for a collection. If you define a comparator, it will be used to maintain the collection in sorted order. This means that as models are added, they are inserted at the correct index in collection.models.

You've given your collection a comparator. Therefore your collection will always be sorted as specified by your comparator.

Also, your comparator is broken. A two-argument comparator should return -1, 0, or 1 just like the comparator function you use with the standard Array.prototype.sort. You could use either of these:

people.comparator = 'name';
people.comparator = function(m) { return m.get('name') }

to properly sort your collection by name.