Backbone.js Series Tutorial 12: Backbone.collection

Source: Internet
Author: User
Tags add array object constructor end extend sort tojson

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.

 
  
  
  1. var Contact1model = new Backbone.model ({
  2. FirstName: "John",
  3. LastName: "Doe",
  4. Phone: "1-111-1111"
  5. });
  6. var Contact2model = new Backbone.model ({
  7. FirstName: "Jane",
  8. LastName: "Doe",
  9. Phone: "2-222-2222"
  10. });
  11. Create a collection and pass in two models
  12. var contacts = new Backbone.collection ([Contact1model, Contact2model]);
  13. Console.log (Contacts.models); Log, background output contains an array of models

Tips:

    1. 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.
    2. The second argument passed to the collection constructor is an option object that is used to configure the url,model,comparater option.
    3. 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.
    4. 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.
    5. The length property is available on the collection instance, maintaining the number of models that the collection contains.
    6. 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.

 
  
  
  1. var Contactmodel = Backbone.Model.extend ({//Inheritance Backbone.model
  2. Defaults: {firstName: "No Name Yet", LastName: "No Last Name Yet"}
  3. });
  4. var contactdata = [
  5. {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"}
  6. ];
  7. Create a collection from model constructors and data
  8. var contacts = new Backbone.collection (Contactdata,{model:contactmodel});
  9. 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:

    1. The Model property can also be set during the Backbone.collection constructor of a subcategory (Contactscollection = Backbone.Collections.extend ({model: Modelconstructor}).
    2. 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.

 
  
  
  1. var contactdata = [
  2. {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"}
  3. ];
  4. Create a collection from model constructors and data
  5. var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
  6. Console.log (Contacts.tojson ());
  7. [{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.

 
  
  
  1. var contactdata = [
  2. {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"},
  3. {firstName: "Cody", LastName: "Lindley", Phone: "3-333-3333"}
  4. ];
  5. var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
  6. This model property provides an array that accesses the storage model in a collection
  7. 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.

 
  
  
  1. var contactdata = [
  2. {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"},
  3. {firstName: "Cody", LastName: "Lindley", Phone: "3-333-3333"},
  4. ];
  5. var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
  6. Use where () to return a model containing only John and Jane from contacts
  7. 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.

 
 
  1. var Contact1model = new Backbone.model ({id:01,firstname: "John", LastName: "Doe", Phone: "1-111-1111"
  2. });
  3. var contacts = new Backbone.collection (Contact1model);
  4. All of the following returns a reference to the Contact1model in the contact set
  5. Using Get ()
  6. Console.log (Contacts.get (Contact1model));
  7. Console.log (Contacts.get (01));
  8. Console.log (Contacts.get ("C1"));
  9. Using at ()
  10. Console.log (contacts.at (0));
  11. Using Findwhere ()
  12. Console.log (Contacts.findwhere ({lastName: "Doe"});
  13. Note that each method returns a reference to the Contact1model
  14. Console.log (Contacts.get (contact1model) = = Contact1model);
  15. Console.log (contacts.get) = = Contact1model);
  16. Console.log (Contacts.get ("c1") = = = Contact1model);
  17. Console.log (contacts.at (0) = = Contact1model);
  18. Console.log (Contacts.findwhere ({lastName: "Doe"}) = = = Contact1model);

Tips:

    1. You should avoid manipulating a collection module by directly altering the model arrangement, or you will not trigger events such as add or remove .
    2. Findwhere () will return the matching value in the first collection.
    3. The at () function is to sort the model on the collection, or to return the model according to the insertion order.
    4. 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.

 
 
    1. var Contactmodel = Backbone.Model.extend ();
    2. var contactdata = [
    3. {firstName: "John", LastName: "Doe", Phone: "1-111-1111"},
    4. {firstName: "Jane", LastName: "Doe", Phone: "2-222-2222"},
    5. {firstName: "Cody", LastName: "Lindley", Phone: "3-333-3333"}
    6. ];
    7. var contacts = new Backbone.collection (contactdata,{
    8. Model:contactmodel,
    9. Comparator: "FirstName"//Let the model be sorted in FirstName order
    10. });
    11. Console.log (//log, Output Cody Jane John, note that this is not the order of the additions
    12. Contacts.models[0].get ("FirstName"),
    13. Contacts.models[1].get ("FirstName"),
    14. Contacts.models[2].get ("FirstName")
    15. );

Tips:

    1. 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.
    2. Calling sort () on the collection triggers a sort event.
    3. 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.

 
  
  
  1. var contacta = new Backbone.model ({firstName: "Luke"});
  2. var CONTACTB = new Backbone.model ({firstName: "John"});
  3. var contactc = new Backbone.model ({firstName: "Bill"});
  4. var contacts = new Backbone.collection ([CONTACTA,CONTACTB,CONTACTC]);
  5. Log ["Luke", "John", "Bill"], note that the order is the same as when it was added
  6. 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.

 
 
    1. var contacta = new Backbone.model ({firstName: "Luke"});
    2. var CONTACTB = new Backbone.model ({firstName: "John"});
    3. var contactc = new Backbone.model ({firstName: "Bill"});
    4. var contactsd = [{firstName: "Jane"},{firstname: "Cody"}];
    5. var contacts = new Backbone.collection ([],{model:backbone.model});
    6.  
    7. //Add data/Property Objects
    8. contacts.add ({firstName: "Jill"});
    9. //adds a set of data/Property objects Contacts.add (CONTACTSD);
    10. //Add model instance
    11. contacts.add (contacta);
    12. //add a set of model instances
    13. contacts.add ([CONTACTB,CONTACTC]);
    14.  
    15. //log ["Jill", "Jane", "Cody", "Luke", "John", "Bill"]
    16. 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:

    1. The {at:index} option is passed to Add ()as the second parameter, and the model is spliced on the collection-specific index.
    2. 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.
    3. 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.

 
  
  
  1. var contacts = New Backbone.collection ([
  2. {firstName: "Luke"},{firstname: "John"},
  3. {Firstna Me: "Bill"},{firstname: "Jill"}
  4. ],{model:backbone.model});
  5.  
  6. //remove the Luke model from the collection
  7. contacts.remove (Contacts.findwhere ({firstName: "Luke"});
  8. //deletes a set of model instances
  9. contacts.remove ([
  10. Contacts.findwhere ({firstName: "Bill"})
  11.  
  12. //validation model has been deleted
  13. 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:

    1. Calling remove ()without parameters does not delete all models. If you need to delete all models, you should call Reset ()without parameters.
    2. 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.

 
  
  
  1. var contacts = new Backbone.collection ([
  2. {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"},
  3. ],{model:backbone.model});
  4. Console.log (Json.stringify (Contacts.tojson ())); Check current model attributes
  5. Add Bill Doe, delete Jane Doe, update John Doe
  6. Contacts.set ([
  7. {firstName: "Jane", MiddleName: "Roe", LastName: "Doe", Phone: "555-555-5555"}
  8. ]);
  9. Verifying changes
  10. Console.log (Json.stringify (Contacts.tojson ()));

Tips:

    1. When the set () is used on the model and the collection object, the Add, remove, and change events are also triggered.
    2. 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:

    1. The call Reset () without any arguments deletes all the models from the collection.
    2. 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 ().

 
  
  
  1. var contactdata = [
  2. {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"},
  3. ];
  4. var contacts = new Backbone.collection (Contactdata,{model:backbone.model});
  5. Iterate through each model in the collection and record its property values
  6. Contacts.each (function (model) {
  7. Console.log (Model.values ());
  8. });
  9. Gets the first model in the collection and records its property values
  10. Console.log (Contacts.first (). values ());


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.