backbonejs 默认按字母顺序排序并将模型添加到集合中吗?

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

Fiddle 这里 http://jsfiddle.net/adamchenwei/966pob6c/

脚本在这里:

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

我无法理解为什么这三个对象不是根据其添加顺序而是按字母顺序索引?有没有办法在模型添加到集合后禁用 BB 这样做?

来自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.

您已经给 collection 一个 comparator。因此,您的 collection 将始终按照您的 comparator.

指定的顺序排序

另外,你的 comparator 坏了。 two-argument 比较器应该 return -1、0 或 1,就像您在标准 Array.prototype.sort 中使用的比较器函数一样。您可以使用以下任一方法:

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

按名称正确排序 collection。