最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbonejs collection change sort order? - Stack Overflow

programmeradmin4浏览0评论

How do I change the sort order of a backbone collection after it has already been initialized?

Tried this: Doesn't work

    collectionparator = function () {
      // new function
    }
    collectionObject.sort()

How do I change the sort order of a backbone collection after it has already been initialized?

Tried this: Doesn't work

    collection.parator = function () {
      // new function
    }
    collectionObject.sort()
Share Improve this question asked May 20, 2011 at 3:02 HarryHarry 55.1k76 gold badges187 silver badges270 bronze badges 2
  • Is defining the parator when the collection is intialized not an option? Why not? – Matt Ball Commented May 20, 2011 at 3:21
  • Post more code. How is collection and collectionObject defined? – hyperslug Commented May 20, 2011 at 5:58
Add a ment  | 

2 Answers 2

Reset to default 3

I don't think you are defining the parator correctly. If you define a parator, 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:

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

chapters.parator = 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 parator 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 parator approach.

It should work if you call sort on the correct collection:

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

collection.sort();
发布评论

评论列表(0)

  1. 暂无评论