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

时间:2015-06-25 19:06:32

标签: backbone.js backbone-collections

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 个答案:

答案 0 :(得分:1)

来自fine manual

  

比较器 collection.models

     

默认情况下,集合没有比较器。如果定义比较器,它将用于按排序顺序维护集合。这意味着,在添加模型时,会将它们插入comparator中的正确索引。

您已为自己的收藏集comparator。因此,您的收藏将始终按照comparator

的指定进行排序

此外,您的people.comparator = 'name'; people.comparator = function(m) { return m.get('name') } 已损坏。双参数比较器应返回-1,0或1,就像您使用标准Array.prototype.sort的比较器函数一样。你可以使用以下任何一种:

Car

按名称对您的收藏品进行正确排序。