Backbone.js学习之Collection

首先,当然是一如既往地看官方文档的解释。

Collections are ordered sets of models.
翻译:

Collections是models的一个集合。

关于book和bookshelf的例子

        var Book = Backbone.Model.extend({
            defaults: {
                title: null
            },
            initialize: function() {
                console.log("hi, you create me!");
            }

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

        var book1 = new Book({title : 'book1'});
        var book2 = new Book({title : 'book2'});
        var book3 = new Book({title : 'book3'});

    //注意这里面是数组,或者使用add
    //var bookShelf = new BookShelf([book1, book2, book3]);

    var bookShelf = new BookShelf;

    bookShelf.add(book1);
    bookShelf.add(book2);
    bookShelf.add(book3);
    bookShelf.remove(book3);

    //基于underscore这个js库,还可以使用each的方法获取collection中的数据
    bookShelf.each(function(book){
        console.log(book.get('title'));
    });

Collection还有很多作用,这里先留个坑。以后学到了在来填!

你可能感兴趣的:(Collection)