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?
From the fine manual:
You've given your collection a
comparator
. Therefore your collection will always be sorted as specified by yourcomparator
.Also, your
comparator
is broken. A two-argument comparator should return -1, 0, or 1 just like the comparator function you use with the standardArray.prototype.sort
. You could use either of these:to properly sort your collection by name.