简而言之,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》 一篇。