集合是模型的组合
eg:- Model: Student, Collection: ClassStudents
- Model: Todo Item, Collection: Todo List
- Model: Animal, Collection: Zoo
通常你只会使用一种类型的模型,但模型本身并不局限于一种集合;
- Model: Student, Collection: Gym Class (体育课)
- Model: Student, Collection: Art Class (艺术课)
- Model: Student, Collection: English Class (英语课)
var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
},
initialize: function(){
console.log("Music is the answer");
}
});
var Album = Backbone.Collection.extend({
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]
toJSONtoJSO方法返回集合中包含哈每个模型哈希属性的数组。此方法通常用于对集合整体做序列化和持久化。
var song = new Backbone.Collection([
{name: "Flatts"},
{name: "OMC"},
{name: "Jackson"}
]);
JSON.stringify(song); //[{"name":"Flatts"},{"name":"OMC"},{"name":"Jackson"}]
song.toJSON(); //[Object { name="Flatts"}, Object { name="OMC"}, Object { name="Jackson"}]
比较器Comparatorvar student = Backbone.Model;
var students = new Backbone.Collection;
students.comparator = 'name'; //按name属性正序排序,
students.add(new student({name: "name1", roll: 9}));
students.add(new student({name: "name2", roll: 5}));
students.add(new student({name: "name3", roll: 1}));
//从集合中的每个模型采摘一个属性,这等同于从迭代器调用Map并返回单一属性
students.pluck('roll'); // [9, 5, 1]
采摘
Pluck:从集合中的每个模型采摘一个属性,这等同于从迭代器调用Map并返回单一属性。
var song = new Backbone.Collection([
{name: "Flatts"},
{name: "OMC"},
{name: "Jackson"}
]);
var names = song.pluck("name");
JSON.stringify(names); //["Flatts","OMC","Jackson"]
Wherewhere:返回集合中所有匹配传递的属性的模型的数组,使用了过滤器。
var song = new Backbone.Collection([
{name: "Yes I Do", artist: "Flatts"},
{name: "How Bizarre", artist: "How Bizarre"},
{name: "What Hurts the Most", artist: "Flatts"},
]);
var artists = song.where({artist: "Flatts"});
JSON.stringify(artists); //[{"name":"Yes I Do","artist":"Flatts"},{"name":"What Hurts the Most","artist":"Flatts"}]