Backbone.collection Overview
A backbone set represents a set of logically ordered combinations of models and provides methods and properties for using (combining, classifying, filtering) these model groups. To illustrate this in this article (model = a row of tagged contact data in a form), you can think of a set as the entire form, which contains many lines of contact data. Below I have updated the details of the contact in the form, as we explained at the beginning of the previous chapter, so that the entire form can be treated as a contact form.
Of course, a backbone.collection is more than just a label like the previous form. The collection can also capture the model and the events that are triggered on the collection (change, destroy, request, sync, error, void). It also contains a series of useful events (add, remove, reset, categorize, request, sync).
Tips:
- In the simplest form, a collection is an array containing the reference to the model instance. In fact, each collection instance provides a models property as a direct reference to an array of internal model instances.
Create a backbone.collection from the model instance
To create a universal collection, we only need to instantiate an instance by Backbone.collection, and then pass in a row of model instances. In the following code, I created the contact model discussed in the previous section and passed it to a collection as the first selection.
- var Contact1model = new Backbone.model ({
- FirstName: "John",
- LastName: "Doe",
- Phone: "1-111-1111"
- });
- var Contact2model = new Backbone.model ({
- FirstName: "Jane",
- LastName: "Doe",
- Phone: "2-222-2222"
- });
- Create a collection and pass in two models
- var contacts = new Backbone.collection ([Contact1model, Contact2model]);
- Console.log (Contacts.models); Log, background output contains an array of models
Tips:
- The first argument passed when instantiating a collection can be either a model instance or a set of model instances. However, if the collection that you create has a reference to a model constructor (through the Model property), the collection can instantiate the model internally by passing a raw property/data object or a set of raw properties/data Objects.
- The second argument passed to the collection constructor is an option object that is used to configure the url,model,comparater option.
- Similar to Backbone.view and Backbone.model, a backbone.collection is extended (subcategory) using extend () and defines a initialize function, When the collection is created, the initialization function is called.
- The Clone () method provides that a collection object can be created by cloning a collection instance. When you use clone () , a new collection instance that contains the same model is returned.
- The length property is available on the collection instance, maintaining the number of models that the collection contains.
- When you add a model to the collection, the collection property of the model is automatically updated and contains a reference to the collection.
Created by a model constructor backbone.collection
The common pattern for creating a collection is to point the Model property of the collection to a modeling constructor, and then you do not need to pass in a reference to a set of model instances, which itself can instantiate the model from the original data and store the instances in the collection.
In the following code, when a collection is instantiated, a set of raw data and a model constructor (Contactmodel) are passed to the Backbone.collection constructor.
- var Contactmodel = Backbone.Model.extend ({//Inheritance Backbone.model
- Defaults: {firstName: "No Name Yet", LastName: "No Last Name Yet"}
- });
- var contactdata = [
- {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"}
- ];
- Create a collection from model constructors and data
- var contacts = new Backbone.collection (Contactdata,{model:contactmodel});
- Console.log (Contacts.models); Log, output the array containing the model
This is exactly the same as the result of passing in a reference to the created model, but by using the Model property, the collection can complete some setup steps for us.
Tips:
- The Model property can also be set during the Backbone.collection constructor of a subcategory (Contactscollection = Backbone.Collections.extend ({model: Modelconstructor}).
- The Model property can either point to a modeling constructor, or it can be a function value that returns a model instance.
Backbone.collection methods, properties, and events
The Backbone.collection collection instance has the following methods and properties:
- Model
- Models
- Tojson
- Sync
- Underscore Methods (28)
- Add
- Remove
- Reset
- Set
- Get
- At
- Push
- Pop
- Unshift
- Shift
- Slice
- Length
- Comparator
- Sort
- Pluck
- where
- Findwhere
- Url
- Parse
- Clone
- Fetch
- Create
The methods or properties shown in bold are not described in this article and we will discuss these synchronization-related methods or properties in future articles.
In addition, the collection can take advantage of the following embedded events:
Tips:
- Because the collection contains the model, events triggered on the model can also be triggered on the collection, which means that you can listen on a collection (Contacts.on ("Change", function (model,options) {}) a model of the Change, Change[:attribute], destroy, error, invalid event.
Use Tojson () to get all model data/attributes on a collection
The Tojson () method of the collection returns an array that contains a copy of the internal properties of each model in the collection. In the following code, I use Tojson () to output an array that contains all the properties of each model in the collection.
- var contactdata = [
- {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"}
- ];
- Create a collection from model constructors and data
- var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
- Console.log (Contacts.tojson ());
- [{firstname= "John", lastname= "Doe", ...}, {firstname= "Jane", lastname= "Doe", ...}] */
Using models, get (), in (), where (), Findwhere () Gets the model from a set
The models property provides direct access to a set of data, including all references to the model to the collection. We have used this attribute in the previous section, but in order to demonstrate its value, in the following code, a set of model instances (i.e. model objects) are extracted from a set using the models property.
- var contactdata = [
- {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"},
- {firstName: "Cody", LastName: "Lindley", Phone: "3-333-3333"}
- ];
- var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
- This model property provides an array that accesses the storage model in a collection
- Console.log (Contacts.models);
The where () method provides an array of models that can be filtered by attributes. In the following code, I use the where () to get a set of models that contain only the {firstName: "Doe"} attribute in the collection.
- var contactdata = [
- {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"},
- {firstName: "Cody", LastName: "Lindley", Phone: "3-333-3333"},
- ];
- var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
- Use where () to return a model containing only John and Jane from contacts
- Console.log (Contacts.where ({lastName: "Doe"});
Using Get (), the at (), the Findwhere () collection method, we can obtain a single model reference instead of a set of model references. In the following code I will demonstrate these three methods.
- var Contact1model = new Backbone.model ({id:01,firstname: "John", LastName: "Doe", Phone: "1-111-1111"
- });
- var contacts = new Backbone.collection (Contact1model);
- All of the following returns a reference to the Contact1model in the contact set
- Using Get ()
- Console.log (Contacts.get (Contact1model));
- Console.log (Contacts.get (01));
- Console.log (Contacts.get ("C1"));
- Using at ()
- Console.log (contacts.at (0));
- Using Findwhere ()
- Console.log (Contacts.findwhere ({lastName: "Doe"});
- Note that each method returns a reference to the Contact1model
- Console.log (Contacts.get (contact1model) = = Contact1model);
- Console.log (contacts.get) = = Contact1model);
- Console.log (Contacts.get ("c1") = = = Contact1model);
- Console.log (contacts.at (0) = = Contact1model);
- Console.log (Contacts.findwhere ({lastName: "Doe"}) = = = Contact1model);
Tips:
- You should avoid manipulating a collection module by directly altering the model arrangement, or you will not trigger events such as add or remove .
- Findwhere () will return the matching value in the first collection.
- The at () function is to sort the model on the collection, or to return the model according to the insertion order.
- The Slice () method of a set is a brief expression of Models.slice (Begin,end).
Collection sorting
By default, the collection itself cannot be sorted by itself. Models are simply arranged in the order in which they are added. In order for a set to be sorted in a particular order, you should define the comparator property, if you accept only one argument as a sortby function, and if you receive two arguments as a sort function, Or as a string indicating that the property is sorted. In the following code, we pass the comparer value during collection creation, so the collection can sort the model by FirstName.
- var Contactmodel = Backbone.Model.extend ();
- var contactdata = [
- {firstName: "John", LastName: "Doe", Phone: "1-111-1111"},
- {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"},
- {firstName: "Cody", LastName: "Lindley", Phone: "3-333-3333"}
- ];
- var contacts = new Backbone.collection (contactdata,{
- Model:contactmodel,
- Comparator: "FirstName"//Let the model be sorted in FirstName order
- });
- Console.log (//log, Output Cody Jane John, note that this is not the order of the additions
- Contacts.models[0].get ("FirstName"),
- Contacts.models[1].get ("FirstName"),
- Contacts.models[2].get ("FirstName")
- );
Tips:
- A change in a collection (that is, Add ()) automatically invokes the sort logic defined by comparator . However, if a model's properties change, you need to manually sort () the collection to update and sort correctly.
- Calling sort () on the collection triggers a sort event.
- The comparer value can be set after the collection is created by defining a sort value (that is, sort , sortby function, or Sort property) for the comparer value of the collection.
Use Pluck () in the collection to get the Model attribute array and the property value array for each model
The Pluck () method is useful for creating an array of all the property values of a particular property in the Model collection. For example, in the following code, I set up a collection of three models, all with firstName attributes. I invoke the pluck ("FirstName") method on the collection to extract the FirstName value of each model.
- var contacta = new Backbone.model ({firstName: "Luke"});
- var CONTACTB = new Backbone.model ({firstName: "John"});
- var contactc = new Backbone.model ({firstName: "Bill"});
- var contacts = new Backbone.collection ([CONTACTA,CONTACTB,CONTACTC]);
- Log ["Luke", "John", "Bill"], note that the order is the same as when it was added
- Console.log (Contacts.pluck ("FirstName"));
Using Add (), push (), unshift () to add a model to a collection
The Add () method is used to add a model to a collection and to add a single model instance or set of model instances. If you set a value for the model property of a collection, you can pass the original data/Property object, or a set of raw data/property objects. In the following code, I demonstrate the use of these methods to add a model to the collection.
- var contacta = new Backbone.model ({firstName: "Luke"});
- var CONTACTB = new Backbone.model ({firstName: "John"});
- var contactc = new Backbone.model ({firstName: "Bill"});
- var contactsd = [{firstName: "Jane"},{firstname: "Cody"}];
- var contacts = new Backbone.collection ([],{model:backbone.model});
-  
- //Add data/Property Objects
- contacts.add ({firstName: "Jill"});
- //adds a set of data/Property objects Contacts.add (CONTACTSD);
- //Add model instance
- contacts.add (contacta);
- //add a set of model instances
- contacts.add ([CONTACTB,CONTACTC]);
-  
- //log ["Jill", "Jane", "Cody", "Luke", "John", "Bill"]
- console.log (Contacts.pluck ("FirstName"));
The push () and unshift () method functions are equivalent to the Add () method and receive the same parameters, except push ( ) and unshift () Method one is to add the model at the end of the collection (push ()) and the other is to add the model in the initial collection (unshift ()).
Tips:
- The {at:index} option is passed to Add ()as the second parameter, and the model is spliced on the collection-specific index.
- Add two times to a collection the same model is not valid, and the model is ignored unless you pass the {merge:true} option as the second argument to the add () method. If a merge occurs, a change event is triggered on both the model and the collection.
- When you add, push, or convert a model to a collection, the Add event is triggered.
Using Remove (), pop (), Shift () to delete a model from a collection
The Remove () method can be used to delete a model from the collection by passing a reference to the desired deletion model. I'll show you how to remove a single model or several models from a collection.
- var contacts = New Backbone.collection ([
- {firstName: "Luke"},{firstname: "John"},
- {Firstna Me: "Bill"},{firstname: "Jill"}
- ],{model:backbone.model});
-  
- //remove the Luke model from the collection
- contacts.remove (Contacts.findwhere ({firstName: "Luke"});
- //deletes a set of model instances
- contacts.remove ([
-
- Contacts.findwhere ({firstName: "Bill"})
-
-  
- //validation model has been deleted
- console.log (Contacts.pluck ("FirstName"))//logs ["Jill"], Luke, John, Bill were removed
pop () and shift () are convenient ways to delete a model. Calling pop () deletes the last model in the collection, and dropping shift () deletes the first model in the collection.
Tips:
- Calling remove ()without parameters does not delete all models. If you need to delete all models, you should call Reset ()without parameters.
- When remove (), pop (), Shift () is invoked, a remove event is triggered.
Use Set () to add, merge, and delete models at the same time
The set () method can update the state of the model in the collection by matching the changes in the model instance array passed to the set () method. That is, using the set () method will attempt to synchronize the state of the incoming model array with the internal model of the collection, by intelligently deciphering the differences and adding, deleting, merging according to the differences.
In the following code, I set up a collection and use set () in the collection to delete a model, and then update a model.
- var contacts = new Backbone.collection ([
- {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"},
- ],{model:backbone.model});
- Console.log (Json.stringify (Contacts.tojson ())); Check current model attributes
- Add Bill Doe, delete Jane Doe, update John Doe
- Contacts.set ([
- {firstName: "Jane", MiddleName: "Roe", LastName: "Doe", Phone: "555-555-5555"}
- ]);
- Verifying changes
- Console.log (Json.stringify (Contacts.tojson ()));
Tips:
- When the set () is used on the model and the collection object, the Add, remove, and change events are also triggered.
- You can pass {add:false}, {remove:false}, or {merge:false} option to set (), so that its add, delete, merge function does not work.
Use Reset () in a collection to replace all models (that is, bulk replacement/reset)
Use the Rese () method to replace the original model with a (or a series) of new models in a collection. This is actually similar to deleting the original model in the collection and adding a new model.
Tips:
- The call Reset () without any arguments deletes all the models from the collection.
- When the reset () method is used, a reset event is triggered.
Using the Underscore.js (or Lodash.js) method in the collection model
A collection instance can have many usages to manipulate the array of models that the collection instance contains. Note, however, that backbone the following underscore.js (or Lodash.js) methods into the collection's prototype chain, which are also useful (Mycollectioninstance.first () and mycollectioninstance.at (0) is the same).
- ForEach or each
- Map or Collect
- Reduce or FOLDL or inject)
- Reduceright or Foldr
- Find or Detect
- Filter or select
- Reject
- Every or all
- Some or any
- Contains or include
- Invoke
- Max
- Min
- SortBy
- GroupBy
- Sortedindex
- Shuffle
- ToArray
- Size
- A or take
- Initial
- Rest or tail
- Last
- Without
- IndexOf
- LastIndexOf
- IsEmpty
- Chain
In the following code example, I used each () and the I ().
- var contactdata = [
- {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"},
- ];
- var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
- Iterate through each model in the collection and record its property values
- Contacts.each (function (model) {
- Console.log (Model.values ());
- });
- Gets the first model in the collection and records its property values
- Console.log (Contacts.first (). values ());