Details about the set in Backbone. js and backbone. js
The set of Backbone. js is just a simple ordered set model. By adapting to models and sets, we can avoid putting data processing logic to our view layer. In addition, models and collections provide convenient methods to work with the backend. When data changes, you can automatically mark the Backbone. js view. In this way, it can be used in the following situations:
Copy codeThe Code is as follows:
Model: Animal, Collection: Zoo
Generally, your set only adapts to one model, but the model itself is not limited to the set type.
Copy codeThe Code is as follows:
Model: person, Collection: Office
Model: person, Collection: Home
The following is an example of a common model/set:
Copy codeThe Code 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 code above shows how to create a set. However, it does not tell us how to manipulate a set with data. Therefore, let's explore this process:
Copy codeThe Code 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 collection of Backbone. js and other components:
1. Add a model to a set
As we know, a set is a set of models. Therefore, we can add a model to the set. To add a model to a set, we can use the add method. We can also add a model to the beginning of the Set-by using the unshift method.
Copy codeThe Code 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 ));
Ii. Remove a model from the set
In many cases, we need to remove some specified data from the collection. To remove a model from a set, we need to provide the model id. If we want to replace the original set with a complete new dataset, we can use the reset method.
Copy codeThe Code is as follows:
Music. remove (1 );
Console. log ('How Bizarre removed ...');
Console. log (JSON. stringify (Music ));
3. Get and Set
If we need to obtain a value from the collection in other parts of the code, we can directly use the get method. At this point, we pass the ID value to the model with the search.
Copy codeThe Code is as follows:
Console. log (JSON. stringify (Music. get (2 )));
The set Method of a set has an interesting implementation. The set Method transmits the model list to perform the "smart" Update of the set. If the model in the list is not in the collection, it is added to the set. If the model is already in the Set, its attributes are merged. If the set contains any model that does not belong to the list, the model will be removed.
Copy codeThe Code is as follows:
Var Music = Backbone. Model. extend ({
// This attribute shocould be set as a default
Defaults :{
Name :''
},
// Set the id attribute so that the collection
Idattri': '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 ('delete', function (){
Alert ('add ')
});
Models = [{
Name: 'omc ',
Id: 1
},{
Name: 'flatts ',
Id: 2
},{
Name: 'Jackson ',
Id: 3
}];
Collection. add (models );
});
As we have seen above, we already have two models. When we add 3rd models, the previous models remain unchanged.
Iv. constructor and initialization
When we create a set, we can pass the initialization array of the model. The comparator of the set can be added as an option. If the passed comparator option is false, sorting is blocked. If we define an initialization function, this function will be called when the set is created. The following describes several options. If they are provided, they are directly added to the set: Model and comparator.
Copy codeThe Code is as follows:
Var tabs = new TabSet ([tab1, tab2, tab3]);
Var spaces = new Backbone. Collection ([], {
Model: Space
});
V. toJSON
The toJSO method returns an array that contains the hash attributes of each model. This method is usually used for serialization and persistence of the entire set.
Copy codeThe Code is as follows:
Var song = new Backbone. Collection ([
{Name: "Flatts "},
{Name: "OMC "},
{Name: "Jackson "}
]);
Alert (JSON. stringify (song ));
6. Comparator
By default, the set does not contain a comparator. If we define a comparator, it can be used to maintain a certain sort of the set. This means that when a model is added, the model will be inserted to a suitable position in the set. The comparator can be defined by sortBy or indicated by a string.
The sortBy comparator function returns a model and a number or string.
The sort comparator function obtains two models. If the first model prevails over the second model,-1 is returned. If the two models have the same level, 0 is returned. If the second model prevails over the first model, then 1 is returned.
Let's take a look at the example below:
Copy codeThe Code 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 will not be automatically reordered, even if we modify the attributes of the model. Therefore, we should call the sort method when modifying the model attribute to estimate whether the sorting will be affected.
VII. Sorting
When adding models to a set, the set should be forcibly re-ordered. To disable sorting when adding models to a set, you can pass the {sort: false} parameter. Call the sort trigger to check this parameter.
Copy codeThe Code is as follows:
SortByType: function (type ){
This. sortKey = type;
This. sort ();
}
And view functions:
Copy codeThe Code is as follows:
SortThingsByColumn: function (event ){
Var type = event. currentTarget. classList [0]
This. collections. things. sortByType (type)
This. render ()
}
8. Picking
Pluck: extracts an attribute from each model in the set. This is equivalent to calling Map from the iterator and returning a single attribute.
Copy codeThe Code 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 all models that match the passed attributes in the set. A filter is used.
Copy codeThe Code 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
Set the URL attribute in the collection to reference the location of the server. The model in the Set uses this URL to construct its own URL.
Copy codeThe Code is as follows:
Var Songs = Backbone. Collection. extend ({
Url: '/songs'
});
Var Songs = Backbone. Collection. extend ({
Url: function (){
Return this.doc ument. url () + '/songs ';
}
});
XI. Analysis
Parse: This is called by Backbone when fetch is extracted, regardless of whether the server returns the set model. This function will pass the original response object, which should return an array of model attributes added to the set. By default, the no-op operation is null. Simply pass through the JSON response, overwrite the operation with the existing API, or better respond to the namespace.
Copy codeThe Code is as follows:
Var songs = Backbone. Collection. extend ({
Parse: function (response ){
Return response. results;
}
});
12. Extraction
Fetch: extracts the default model set of the set from the server. After retrieval, set them in the set. This option is hashed by success or error callback. It passes three parameters (set, response, and option. Then the model data is returned from the server. It is used to set the model for merging and extraction.
Copy codeThe Code is as follows:
Backbone. sync = function (method, model ){
Alert (method + ":" + model. url );
};
Var songs = new Backbone. Collection;
Songs. url = '/songs ';
Songs. fetch ();
As we can see above, only the collection of Backbone has so many methods that mastering them can improve the quality of code.