The collection of Backbone.js is just a simple ordered set model. By adapting to models and collections, we can avoid data processing logic being placed in our view layer. Additionally, models and collections provide convenient ways to work with the backend, and when data changes, Backbone.js views can be automatically marked. In this way, it can be used in the following cases:
The code copy is as follows:
Model: Animal, Collection: Zoo
Usually your set is only suitable for one model, but the model itself is not limited to the type of the set.
The code copy is as follows:
Model: person, Collection: Office
Model: person, Collection: Home
Here are examples of common models/sets:
The code copy is as follows:
var Music = Backbone.Model.extend({
initialize: function(){
console.log("Welcome to the music world");
}
});
var Album = Backbone.Collection.extend({
model: Music
});
The above code tells us how to create a collection. But it doesn't tell us the process of manipulating the set with data. So, let's explore this process:
The code copy is as follows:
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);
Let's take a look at the relationship between the Backbone.js collection and other components:
1. Add a model to the collection
As we know, a set is a collection of models. Therefore, we can add models on the collection. To add a model to a collection, we can use the add method. We can also add the model to the start of the collection - by using the unshift method.
The code copy is as follows:
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));
2. Remove the model from the set
Many times, we have the need to remove some specified data from the collection. To remove the model from the collection, we need to provide the id of the model. If we want to replace the original collection with a complete new dataset, we can use the reset method.
The code copy is as follows:
Music.remove(1);
console.log('How Bizarre removed...');
console.log(JSON.stringify(Music));
3. Get and Set
If we need to get a value from a collection elsewhere in the code, we can use the get method directly. At this point, we pass the ID value to the model with the search.
The code copy is as follows:
console.log(JSON.stringify(Music.get(2)));
There is an interesting implementation of the set method of the set. The set method performs "intelligent" updates of the collection by passing the model list. If the model in the list is not in the collection, it is added to the collection. If the model is already in the collection, its properties are merged. If the collection contains any model that does not belong to the list, the model is removed.
The code copy is as follows:
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);
});
As we saw above, we already had 2 models beforehand, and when we added the 3rd model, the earlier model remained the same.
IV. Constructor and Initialization
When we create a collection, we can pass the initialized array of the model. The comparator of the set can be added as an option. If the passed comparator option is false, sorting is prevented. If we define an initialization function, this function will be called when the collection is created. The following are several options, if provided, will be added directly to the set: model and comparator.
The code copy is as follows:
var tabs = new TabSet([tab1, tab2, tab3]);
var spaces = new Backbone.Collection([], {
model: Space
});
5. toJSON
The toJSO method returns an array in the collection containing each model hash attribute. This method is usually used to serialize and persist the entire set.
The code copy is as follows:
var song = new Backbone.Collection([
{name: "Flatts"},
{name: "OMC"},
{name: "Jackson"}
]);
alert(JSON.stringify(song));
6. Comparator
By default, collections do not have comparators. If we define a comparator, it can be used to keep the set in some sort. This means that when adding a model, the model is inserted into the appropriate location in the collection. Comparator can be defined in sortBy, or indicates sorted properties in a string.
The sortBy comparator function gets a model and returns a number or string.
The sort comparator function obtains two models. If the first model is ahead of the second model, then returns -1; if the two models are of the same level, then returns 0; if the second model is ahead of the first model, then returns 1.
Let's take a look at the example below:
The code copy is as follows:
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'));
The set to be compared is not automatically reordered, even if we modify the properties of the model. Therefore, we should call sorting when the estimation will affect the sort after modifying the model attributes.
7. Sort
When adding models to a collection, the collection should be forced to be reordered. To disable sorting when adding a collection model, you can pass the {sort: false} parameter. Calling the sorted trigger checks this parameter.
The code copy is as follows:
sortByType: function(type) {
this.sortKey = type;
this.sort();
}
And view functions:
The code copy is as follows:
sortThingsByColumn: function(event) {
var type = event.currentTarget.classList[0]
this.collections.things.sortByType(type)
this.render()
}
8. Picking
Pluck: Pick one attribute from each model in the collection, which is equivalent to calling the Map from the iterator and returning a single attribute.
The code copy is as follows:
var song = new Backbone.Collection([
{name: "Flatts"},
{name: "OMC"},
{name: "Jackson"}
]);
var names = songs.pluck("name");
alert(JSON.stringify(names));
9. Where
where: Returns an array of models in the collection that matches the passed properties, using filters.
The code copy is as follows:
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);
10. URL
Setting URL properties in the collection will refer to the server's location. The models within the collection will use this URL to construct their own URL.
The code copy is as follows:
var Songs = Backbone.Collection.extend({
url: '/songs'
});
var Songs = Backbone.Collection.extend({
url: function() {
return this.document.url() + '/songs';
}
});
11. Analysis
Parse: Called by Backbone when fetching, regardless of whether the server returns the collection's model. This function passes the original response object, which should return an array of model properties added to the collection. The default implementation is no-op operation. Simple pass through JSON response, overwrite this with a pre-existing API, or better namespace response.
The code copy is as follows:
var songs = Backbone.Collection.extend({
parse: function(response) {
return response.results;
}
});
12. Extraction
Fetch: Extract the default model set of the collection from the server, and set them in the collection after retrieval. This option hash accepts success or error callbacks, which passes three parameters (set, response, option). Then return the model data from the server. It is used to set up the merged extracted model.
The code copy is as follows:
Backbone.sync = function(method, model) {
alert(method + ": " + model.url);
};
var songs = new Backbone.Collection;
songs.url = '/songs';
songs.fetch();
As you can see above, there are so many ways to master them to improve the quality of your code.