作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs
四、构造器与初始化
当我们创建一个集合时,我们可以传递模型的初始化数组。集合的比较器可以作为一个选项被加入。如果传递的比较器选项是false,那么会阻止排序。如果我们定义了一个初始化函数,那么此函数会在集合创建时被调用。下面说明了几个选项,如果提供了,会直接加到集合上:模型和比较器。
var tabs = new TabSet([tab1, tab2, tab3]); var spaces = new Backbone.Collection([], { model: Space });
var song = new Backbone.Collection([ {name: "Flatts"}, {name: "OMC"}, {name: "Jackson"} ]); alert(JSON.stringify(song));
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'));
sortByType: function(type) { this.sortKey = type; this.sort(); }
sortThingsByColumn: function(event) { var type = event.currentTarget.classList[0] this.collections.things.sortByType(type) this.render() }
var song = new Backbone.Collection([ {name: "Flatts"}, {name: "OMC"}, {name: "Jackson"} ]); var names = songs.pluck("name"); alert(JSON.stringify(names));
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();