简而言之,Backbone
中的 Collection
就是 Model
的一个有序集合,比如,它可能会在以下情况中用到:
- Model: Student, Collection: ClassStudents
- Model: Todo Item, Collection: Todo List
- Model: Animal, Collection: Zoo
Collection
一般只使用同一类型的 Model
,但是 Model
可以属于不同类型的 Collection
,比如:
- Model: Student, Collection: Gym Class
- Model: Student, Collection: Art Class
- Model: Student, Collection: English Class
创建一个 Collection
//定义 Model Song
var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
},
initialize: function(){
console.log("Music is the answer");
}
});
//定义 Collection Album
var Album = Backbone.Collection.extend({
model: Song //指定 Collection 内的 Model 为 Song
});
var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });
var myAlbum = new Album([ song1, song2, song3]);
console.log( myAlbum.models ); // 输出为 [song1, song2, song3]
Backbone
的 Collection
概念比较简单,它只是 Model
的一个有序集合,所以对 Model
的相关操作,同样可以对 Collection
应用,详细可以阅读 《认识 Backbone(一) : 什么是 Model》 一篇。