This article mainly introduces Backbone. details about the set in js. This article focuses on Backbone. the relationship between js collections and other components. For more information, see Backbone. javaScript collections are just a simple model of ordered sets. 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:
The 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.
The code is as follows:
Model: person, Collection: Office
Model: person, Collection: Home
The following is an example of a common model/set:
The 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:
The 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.
The 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.
The 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.
The 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.
The 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.
The 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.
The 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:
The 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.
The code is as follows:
SortByType: function (type ){
This. sortKey = type;
This. sort ();
}
And view functions:
The 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.
The 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.
The 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.
The 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.
The 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.
The 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.