简体   繁体   English

Backbonejs集合改变排序顺序?

[英]Backbonejs collection change sort order?

How do I change the sort order of a backbone collection after it has already been initialized? 如何在骨干集合初始化之后更改它的排序顺序?

Tried this: Doesn't work 试过这个:不行

    collection.comparator = function () {
      // new function
    }
    collectionObject.sort()

I don't think you are defining the comparator correctly. 我认为你没有正确定义比较器。 If you define a comparator, objects will be inserted into the collection in the right order. 如果定义比较器,对象将按正确的顺序插入到集合中。

Here is an example you can just run through firebug on a site with backbone loaded: 这是一个示例,您可以在加载了主干的站点上运行firebug:

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) { 
  return chapter.get("page");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

chapters.pluck('title');

# OUTPUT
# ["The Beginning", "The Middle", "The End"]

Notice how the comparator returns the value stored in the page attribute of each chapter. 注意比较器如何返回存储在每章的页面属性中的值。 Backbone's collection sorting acts like a sortBy which uses strings or ints, and doesnt follow a traditional -1,0,1 comparator approach. Backbone的集合排序就像sortBy一样使用字符串或整数,并且不遵循传统的-1,0,1比较器方法。

It should work if you call sort on the correct collection: 如果你在正确的集合上调用sort,它应该工作:

collection.comparator = function (item) {
  return item.get('field');
};

collection.sort();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM