Backbone.js的集合只是一个简单的有序集的模型。通过适应模型和集合,我们可以避免数据处理逻辑放到了我们的视图层。此外,模型和集合还提供了便利的与后端一起工作的方法,当数据发生变化时,可以自动化地标记Backbone.js视图。这样,它可以用于如下的情况:
Model: Animal, Collection: Zoo
Model: person, Collection: Office Model: person, Collection: Home
var Music = Backbone.Model.extend({ initialize: function(){ console.log("Welcome to the music world"); } }); var Album = Backbone.Collection.extend({ model: Music });
上面的代码告诉我们如何创建集合。但是它没有告诉我们用数据操纵集合的过程。因此,让我们探索这个过程:
var Music = Backbone.Model.extend({ defaults: { name: "Not specified", artist: "Not specified" }, initialize: function(){ console.log("Welcome to the music world "); } }); var Album = Backbone.Collection.extend({ model: Music }); var music1 = new Music ({ id: 1 ,name: "How Bizarre", artist: "OMC" }); var music 2 = new Music ({id: 2, name: "What Hurts the Most", artist: “Rascal Flatts" }); var myAlbum = new Album([music 1, music 2]); console.log( myAlbum.models );
一、添加模型到集合
正如我们所知的那样,集合是模型的集合。因此,我们可以在集合上添加模型。要添加模型到集合,我们可以使用add方法。我们还可以添加模型到集合的开始——通过使用unshift方法。
var music3 = new Music({ id: 3, name: "Yes I Do",artist:“Rascal Flatts" }); Music.add(music3); console.log('New Song Added'); console.log(JSON.stringify(Music));
很多时候,我们会有从集合中移除一些指定的数据这样的需求。要从集合中移除模型,我们需要提供模型的id。如果我们想用一个完整的新数据集替换原集合,我们可以使用reset方法。
Music.remove(1); console.log('How Bizarre removed...'); console.log(JSON.stringify(Music));
三、Get和Set
如果我们需要从代码其它地方的集合中获取一个值,那么可以直接使用get方法。此时,我们向带检索的模型传递ID值。
console.log(JSON.stringify(Music.get(2)));
var Music = Backbone.Model.extend({ // This attribute should be set as a default defaults: { Name: '' }, // Set the id attribute so that the collection idAttribute: 'id' }); var song = Backbone.Collection.extend({ model: Music }); var models = [{ Name: 'OMC', id: 1 }, { Name: 'Flatts', id: 2 }]; var collection = new song(models); collection.bind('add', function (model) { alert('addb') }); collection.bind('remove', function () { alert('add') }); models = [{ Name: 'OMC', id :1 }, { Name: 'Flatts', id: 2 }, { Name: ' Jackson ', id: 3 }]; collection.add(models); });
四、构造器与初始化
当我们创建一个集合时,我们可以传递模型的初始化数组。集合的比较器可以作为一个选项被加入。如果传递的比较器选项是false,那么会阻止排序。如果我们定义了一个初始化函数,那么此函数会在集合创建时被调用。下面说明了几个选项,如果提供了,会直接加到集合上:模型和比较器。
var tabs = new TabSet([tab1, tab2, tab3]); var spaces = new Backbone.Collection([], { model: Space });
五、toJSON
toJSO方法返回集合中包含哈每个模型哈希属性的数组。此方法通常用于对集合整体做序列化和持久化。
var song = new Backbone.Collection([ {name: "Flatts"}, {name: "OMC"}, {name: "Jackson"} ]); alert(JSON.stringify(song));
六、比较器Comparator
默认情况下,集合是不带比较器的。如果我们定义了一个比较器,它可以用于让集合维持某种排序。这意味着在添加模型时,模型会被插入到集合中适合的位置。比较器可以用sortBy定义,或以字符串的方式指示排序的属性。
sortBy比较器函数得到一个模型,并返回一个数字或字符串。
sort比较器函数得到两个模型,如果第一个模型先于第二个模型,那么返回-1;如果两个模型同级,那么返回0;如果第二个模型先于第一个模型,那么返回1。
下面我们来看看例子:
var student = Backbone.Model; var students = new Backbone.Collection; students.comparator = '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})); alert(students.pluck('roll'));
七、排序
当集合中添加模型时,应强制集合进行重新排序。当集合添加模型时要禁用排序,可以传递{sort: false}参数。调用排序的触发器会检查此参数。
sortByType: function(type) { this.sortKey = type; this.sort(); }
sortThingsByColumn: function(event) { var type = event.currentTarget.classList[0] this.collections.things.sortByType(type) this.render() }
Pluck:从集合中的每个模型采摘一个属性,这等同于从迭代器调用Map并返回单一属性。
var song = new Backbone.Collection([ {name: "Flatts"}, {name: "OMC"}, {name: "Jackson"} ]); var names = songs.pluck("name"); alert(JSON.stringify(names));
where:返回集合中所有匹配传递的属性的模型的数组,使用了过滤器。
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"}); alert(artists.length);
var Songs = Backbone.Collection.extend({ url: '/songs' }); var Songs = Backbone.Collection.extend({ url: function() { return this.document.url() + '/songs'; } });
var songs = Backbone.Collection.extend({ parse: function(response) { return response.results; } });
Backbone.sync = function(method, model) { alert(method + ": " + model.url); }; var songs = new Backbone.Collection; songs.url = '/songs'; songs.fetch();
正如上面所看到的,仅仅是Backbone的集合就有那么多的方法,掌握它们才能提高代码的质量。