创建自定义集合

要创建新集合

var Books = Backbone.Collection.extend({
    // books will be sorted by title
    comparator: "title",

    initialize: function(models, options) {
        options = options || {};

        // (Optional) you can play with the models here
        _.each(models, function(model) {
            // do things with each model
        }, this);

        this.customProperty = options.property;
    },
});

所有属性都是可选的,仅作为演示。Backbone.Collection 可以按原样使用。

然后使用它就像:

var myBookArray = [
    { id: 1, title: "Programming frontend application with backbone" },
    { id: 2, title: "Backbone for dummies" },
];

var myLibrary = new Books(myBookArray, {
    property: "my custom property"
});

myLibrary.each(function(book){
    console.log(book.get('title'));
});

将输出:

用骨干
骨干编程前端应用程序用于假人