建立自定義集合

要建立新集合

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'));
});

將輸出:

用骨幹
骨幹程式設計前端應用程式用於假人