如何在backboneJs中对集合进行排序

时间:2014-03-25 09:30:01

标签: backbone.js backbone-collections backbone-model

我正在学习BackboneJs使用的文档和一本名为" Beginning backbone"的书。 但是我被困在分类收集部分几个小时。 也尝试研究,但我发现结果复杂= /

我知道我必须使用比较器,如文档中所示,但我不明白如何将它应用于当前的语法代码

http://backbonejs.org/#Collection-comparator

var Book = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        author: "default author",
        pages: 20
    },
    comparator: function(item)
    {
        //sort by title
        return item.get('title');   
    }
});

var book1 = new Book({ title:"Book of wonders",author:"author1",pages:1 });
var book2 = new Book({ title:"Zelda",author:"author2",pages:2 });
var book3 = new Book({ title: "Drake's out", author: "author3",pages:3});
var book4 = new Book({ title: "AutoCad",author: "author4",pages: 4});

var Library = Backbone.Collection.extend({
    model: Book
});

var library = new Library([book1,book2]);
library.add([book3,book4]); 

library.forEach(function(model){
    console.log('Book is called '+model.get("title"));
});

console.log('Library contains '+library.length+' books');

1 个答案:

答案 0 :(得分:0)

这是一个有效的解决方案,它将按标题对所有内容进行排序。 通过其他任何方式对其进行排序只需更改比较器函数

中的get函数的参数
    var Book = Backbone.Model.extend({
        defaults:
        {
            title: "default title",
            author: "default author",
            pages: 20
        } 
    });

    var book1 = new Book({ title:"Book of wonders",author:"author1",pages:1 });
    var book2 = new Book({ title:"Zelda",author:"author2",pages:2 });
    var book3 = new Book({ title: "Drake's out", author: "author3",pages:3});
    var book4 = new Book({ title: "AutoCad",author: "author4",pages: 4});

    var Library = Backbone.Collection.extend({
        model: Book,
        initialize: function()
        {
            console.log("new collection");
        },
        comparator: function(a,b)
        {
            //sort by title
            return a.get('title') < b.get('title') ? -1 : 1;
        }
    });

    var library = new Library([book1,book2]);
    library.add([book3,book4]); 

    library.sort(); 
    library.forEach(function(model){
        console.log('Book is called '+model.get("title"));
    });

    console.log('Library contains '+library.length+' books');