Backbone.js Series Tutorial 11: Backbone.model

Source: Internet
Author: User
Tags filter array object extend functions inheritance tojson access

Introduction to Backbone.model

A backbone model can be likened to a form structure, a column with a header similar to a form, and a row of data similar to a form. Backbone.model object defines column labels, and then uses predefined and custom methods to wrap the data (that is, attributes) in each row for data conversion, validation, and access control. The Backbone.model creates a model instance or an inherited Backbone.model that provides storage of the object to the actual data. For example, a contact model in a contact application is like the following:

You can compare a Backbone.model constructor to the column headings of a form, whose methods and properties are common to each row of data. An instance created by the constructor to populate the table above with actual data.

 
  
  
  1. i.e.
  2. New Backbone.model (
  3. {firstName: "John", LastName: "Doe", Phone: "1-111-1111"}
  4. );

Note that Backbone.model provides properties and methods for each row of data (for example, get("phone"), and also supports defining your own methods and properties (for example:getfullname ()).

The above mentioned content is only a partial feature of the backbone model. In backbone, there is also a portion of the content that involves using AJAX to synchronize data over HTTP via the RESTful JSON API. In this article, we will not discuss the details about synchronization. This section focuses on the lifecycle of a model (and a collection of models), but does not include synchronizing data.

Subclass and create a Backbone.model

To create a generic data model, we only need to instantiate an instance from Backbone.model, and then pass in the value (that is, the backbone attribute) that the model will store. For example, I created two contact models, one is JohnDoe and the other is JaneDoe.

 
  
   
  1. var Contact1model = new Backbone.model (
  2. {firstName: "John", LastName: "Doe", Phone: "111-111-1111"}
  3. );
  4. var Contact2model = new Backbone.model (
  5. {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"}
  6. );

However, it is more inclined to inherit/classify the base Backbone.model, and then instantiate an instance so that you can add your own domain-specific attributes.

In the following code, I inherited the Backbone.model constructor, created a child constructor (Contactmodel), and defined the getfullname () method, so all created in The Contactmodel model will inherit the Getfullname () method.

 
   
    1. var Contactmodel = Backbone.Model.extend ({//extend Backbone.model
    2. Getfullname:function () {
    3. Return This.get ("firstName") + "" + This.get ("LastName");
    4. }
    5. });
    6. var Contact1model = new Contactmodel (//instantiate Contactmodel instance
    7. {firstName: "John", LastName: "Doe", Phone: "111-111-1111"}
    8. );
    9. var Contact2model = new Contactmodel (//instantiate Contactmodel instance
    10. {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"}
    11. );
    12. Call the Getfullname method on our model
    13. Console.log (Contact1model.getfullname ()); Logs John Doe
    14. Console.log (Contact2model.getfullname ()); Logs Jane Doe

Tips:

    1. When instantiating a model, a set of data can be passed into the location of an object. After that, backbone will transfer the array to an object, by giving the property name of the value (["foo", "Bar"]) of the values ({"1": "foo", "2", "Bar"}).
    2. The second parameter passed by the instantiation model is an option object that contains the collection, URL, UrlRoot , and parse options. Most of them will be elaborated in the next article because they involve synchronizing data.
    3. Don't forget the initialize function, which is set when inheriting the model, to place the logical relationship that the instance of the model needs to run. It is particularly important to note that the this value in the initialization function is the scope of the model instance that is created.
    4. A convenient clone () method is available on the model instance, and a new model instance is returned with a copy of the data from the clone () method call. This is a convenient way to create a model from a model instance.

Backbone.model methods, properties, and events

The backbone model instance contains the following methods and properties:

    • Get
    • Set
    • Escape
    • Has
    • unset
    • Clear
    • Id
    • Idattribute
    • Cid
    • Attributes
    • Changed
    • Defaults
    • Tojson
    • Sync
    • Fetch
    • Save
    • Destroy
    • Underscore Methods: (keys, values, pairs, invert, pick, omit)
    • Validate
    • ValidationError
    • IsValid
    • Url
    • UrlRoot
    • Parse
    • Clone
    • IsNew
    • Haschanged
    • Changedattributes
    • Previous
    • Previousattributes

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 model can also use the following embedded events:

Set the default value/attribute for a model

When inheriting a model, you can set a series of default values to share with all instances. In the following code, I set a default value to firstName and lastName.

 
  
    
  1. var Contactmodel = Backbone.Model.extend ({//Inheritance Backbone.model
  2. Defaults: {
  3. FirstName: "No-name Yet",
  4. LastName: "No last Name yet"
  5. }
  6. });
  7. var Contact1model = new Contactmodel (//Instantiation Model Instance
  8. {firstName: "John"}
  9. );
  10. FirstName is set to John while keeping LastName as the default value
  11. Console.log (Contact1model.get ("FirstName")); Log John
  12. Console.log (Contact1model.get ("LastName")); Log "No last name yet"

If you want the instance to not refer to the same default object, you can provide a default function value that will create a special default value (no reference to the same default object).

 
  
     
  1. var Contactmodel = Backbone.Model.extend ({//Inheritance Backbone.model
  2. Defaults:function () {
  3. This.firstname = "No Name yet";
  4. This.lastname = "No last name yet";
  5. return this;
  6. }
  7. });
  8. var Contact1model = new Contactmodel (//Instantiation Model Instance
  9. {firstName: "John"}
  10. );
  11. FirstName is set to John while keeping LastName default values unchanged
  12. Console.log (Contact1model.get ("FirstName")); Log John
  13. Console.log (Contact1model.get ("LastName")); Log "No last name yet"

In the code above, each instance will use a special default object instead of each instance referencing the same default object.

Model data Setup, change, get, recover, and delete

Backbone provides a common set of methods (set (), has (), get (), unset (), clear ()) to process model data. I'll show you each method below.

 
  
      
  1. var contact = new Backbone.model (); Instantiating a model instance
  2. Set up/Edit data
  3. Contact.set ({firstName: "John", LastName: "Doe", Phone: "1-111-1111"});
  4. Owning the FirstName property, notice that no matter what the value of the property will return True
  5. Get Data
  6. Console.log (Contact.get ("FirstName")); Log John
  7. Recover data
  8. Contact.unset ("LastName");
  9. Verify that the data has been recovered
  10. Console.log (Contact.has ("LastName")); Log False
  11. Clear All data
  12. Contact.clear ();
  13. Verify that the data has been cleared
  14. Console.log (contact.attributes); Log Empty {}

Tips:

    1. These methods should be used instead of directly editing the internal attributes objects so that the events in the model can be triggered correctly.
    2. set (), unset ( ) and Clear () methods can invoke internal change events.
    3. The set () method receives an option object (for example: set ({"Name": "Value", "Name": "Value"}), or two string parameters (for example: Set ("Name", "value")).
    4. set (), unset (), and Clear () methods both receive the {silent:true} option to prevent any backbone embedded event from occurring.
    5. The {validate:true} option and the set () method can be used together to validate these values (for example, set ({"foo": "foo"},{validate:true}) before setting the value.

Accessing a model data/attribute

Backbone provides the attributes property to directly access internal objects that contain a model data.

 
  
       
  1. var Contact1model = new Backbone.model (//instantiate Model instance
  2. {firstName: "John", LastName: "Doe"}
  3. );
  4. Console.log (contact1model.attributes); Log {firstname= "John", Lastname= "Doe"}

Backbone provides direct access to this object, which in general is not directly manipulated. In fact, do not do so. If you want to edit the model data, you can use set (), Get (), unset (), Clear () , or copy (Model.tojson (); attributes The object, edits the copy, and then updates the model with the set () .

Tips:

    • Direct manipulation of the attributes property will not invoke an internal model event.

Use Tojson () to get a copy of the model data/attributes

The Tojson () model method returns a copy of the attributes internal data object.

 
  
        
  1. var Contact1model = new Backbone.model (//Instantiation Model Instance
  2. {firstName: "John", LastName: "Doe"}
  3. );
  4. Console.log (Contact1model.tojson ()); Log {firstname= "John", Lastname= "Doe"}
  5. Note that this is not a reference, but a copy of the Property object
  6. i.e.
  7. Console.log (Contact1model.tojson = = = Contact1model.attributes); Log False

This approach is handy when you need to get a clean copy of an object as a template.

Tips:

    1. Use the Tojson () method to get a shallow clone (_.clone) of the Property object, and any nested objects or arrays will be referenced from the prototype, not copied.
    2. Pass a model instance to json.stringify, using the backbone Tojson () method internally.

Filter model data

Backbone from the underscore.js Library Agent 6 methods (keys (), values (), pairs (), invert (), pick (), omit()), can be used directly on the model data. These functions can help filter the state of the required model data. I'll show you the 4 most commonly used methods below.

 
  
         
  1. var contact = new Backbone.model ({
  2. FirstName: "John", LastName: "Doe", Phone: "1-111-1111"
  3. });
  4. Returns the array/property key for the data
  5. Console.log (Contact.keys ()); Log ["FirstName", "LastName", "phone"]
  6. Returns the array/property value of the data
  7. Console.log (Contact.values ()); Log ["John", "Doe", "1-111-1111"]
  8. Copy the Data/Property object, returning the object containing the selected key
  9. Console.log (Contact.pick ("Phone")); Log {phone= "1-111-1111"}
  10. Copy a data/Property object, returning an object that does not contain a selected key
  11. Console.log (Contact.omit ("FirstName", "LastName")); Log {phone= "1-111-1111"}

Monitor model Change events

When the data in the model changes, the Change event is broadcast at the same time, and usually a view can listen for such events.

In the following code, after the model is created, a view is created to listen for the change event on the model. Any changes to the model data will trigger a change event and, ideally, a new rendering.

 
  
          
  1. var contact= New Backbone.model ();
  2.  
  3. var Contactview = Backbone.View.extend ({
  4. Initialize:function () {
  5. This.listento (contacts," Change ", This.render); Listen to change event on model
  6. Render:function () {
  7. Console.log (" data changed, Re-render ");
  8. }
  9. });
  10.  
  11. new Contactview ();
  12.  
  13. contact.set ({//This will trigger the Change event
  14. FirstName: "John", LastName: "Doe", Phone: " 111-111-1111 "
  15. });
  16.  
  17. contact.unset ("phone");//This triggers the Change event

You can also listen only for changes to a particular property on the model, and you need to assign the property name and change event to a listener ("Change:[attribute]"). For example, here I will change the original code to listen only for FirstName attribute changes on the contact model.

 
  
           
  1. var contact= new Backbone.model ();
  2. var Contactview = Backbone.View.extend ({
  3. Initialize:function () {
  4. Listen for change events on the model
  5. This.listento (Contact, "Change:firstname", This.render);
  6. },
  7. Render:function () {Console.log ("Render a change, data changed");}
  8. });
  9. New Contactview ();
  10. The Change event is activated because we only monitor FirstName
  11. Contact.set ("Phone", "222-222-2222"); No Change Event Trigger

Use Haschanged () and Changedattributes () to verify that a model has changed and changed content

The haschanged () and changedattributes () model methods can verify that changes have taken effect after the last change event, and verify that what has changed.

In the following code, I set up a contact model and immediately change the phone number attribute.

 
  
            
  1. Create a contact model, and no change event is activated when the model is instantiated with data
  2. var contact=new backbone.model ({firstName: "John", LastName: "Doe", Phone: "1-111-1111"});
  3. Make a change
  4. Contact.set ({phone: "2-222-2222"});
  5. Verify that a change has occurred
  6. Console.log (contact.haschanged ()); Logs true
  7. Get properties that have been changed
  8. Console.log (Contact.changedattributes ()); Logs {phone= "2-222-2222"}

Code, the internal change event is called immediately by changing the phone number, and thehaschanged () method returns a Boolean function indicating that the model has changed. In order to get an object that contains a change in the property, you need to invoke the changedattibutes () method on the model.

Using previous () and previousattributes () to get the original property value

The previous () and previousattributes () methods can be used to obtain a property value before the Change event. In the following code, I set up a contact model, changed the phone and firstName Properties, and then took advantage of previous () and previousattributes () method retrieves the previous value of the Number property and all model property states before the last change event.

 
  
             
  1. Create a contact model, and no change event is activated when the model is instantiated with data
  2. var contact=new backbone.model ({firstName: "John", LastName: "Doe", Phone: "111-111-1111"});
  3. Make a change
  4. Contact.set ({phone: "2-222-2222", FirstName: "Jane"});
  5. Get the initial value of the phone number
  6. Console.log (contact.previous ("Phone")); Log 111-111-1111
  7. To get all the property states before the last Change event
  8. Console.log (Contact.previousattributes ()); Log {firstName: "John", LastName: "Doe", Phone: "1

Validating model data before a model is set or stored

A validation function is called to validate data quality before the model data is set or stored (discussed in the next article).

By default, thevalidate property is not yet defined. In order to define a validation function on the model, you can either pass validate:function (attributes,options) {} to extend (), or directly update the validate on the model instance Properties. A validation error trip is simply to return any value from a function that receives false.

In the following code, I set up a validation function for the phone number to ensure that any invalid phone number will not be set ().

 
  
              
  1. var contact = New Backbone.model ({
  2. FirstName: "John", LastName: "Doe", phone:0
  3.  
  4. contact.validate = function (attributes,options) {
  5. var Validphone =/\ (? \d{3}\w?\s? \d{3}\w?\d{4}/.test (Attributes.phone);
  6. if (!validphone) {
  7. returns "Setting or saving Invalid Phone number attempted";
  8. }
  9.  
  10. contact.set ("Phone", "111-1 11-1111 ", {validate:true}); Set
  11. contact.set ("Phone", "111-1-1111", {validate:true});//no set, validation failed
  12. console.log (Contact.get ("Phone"));//No Invalid phone number
  13. console.log ( CONTACT.VALIDATIONERROR); Read the last validation error

The value returned from the validation function, if not false, can refer to the model ValidationError property. In the code we return an invalid message from the validation function and access the ValidationError property, which is the background output.

Tips:

    1. A validate callback function passes all model properties as the first argument, and the second parameter contains the set () or Save () option object to validate the trip.
    2. Validation occurs only when using the Save (),set () method, with the validation:true option, or by using isValid () for manual validation.

Monitor the invalid event for a model

When the validate function of a model fails, the embedded invalid event is broadcast. In the following code, I demonstrate listening to this event and outputting arguments to an invalid callback function.

 
  
               
  1. var contact = new Backbone.model ({firstName: "John", LastName: "Doe"});
  2. Contact.validate = function (attributes,options) {
  3. if (!validphone) {returns "Setting or saving Invalid Phone number attempted";}
  4. };
  5. Backbone to listen for invalid events on the contact model
  6. Backbone.listento (Contact, "Invalid", function (model,error,options) {
  7. Console.log (model,error,options);
  8. });
  9. Set invalid phone number trigger invalid event
  10. Contact.set ("Phone", "111-1-1111", {validate:true}); No set, validation failed

Manually run validate on the model

The Validate function can be invoked manually by calling the IsValid () method. In the following code, the Validate function is set when inheriting the Backbone.model constructor, so all model instances can use this validation function. In the process of creating the model instance, in order to ensure that the data is validated, I will run the validate function when I call initialize to get the invalid data passed.

 
               
  1. var Contactmodel = Backbone.Model.extend ({//extend Backbone.model
  2. Validate:function (attributes,options) {
  3. var phone =/\ (\d{3}\w?\s?\d{3}\w?\d{4}/.test (Attributes.phone);
  4. var firstName =/^[a-z] "? [A-za-z]+ (-[a-za-z]+) $/.test (attributes.firstname);
  5. var lastName =/^[a-z] "? [A-za-z]+ (-[a-za-z]+) $/.test (attributes.lastname);
  6. if (!phone!firstname!lastname) {
  7. Return "Setting, saving, or seeding Invalid Data"
  8. }
  9. },
  10. Initialize:function () {
  11. Run validation, if invalid will output information
  12. if (!this.isvalid ()) {Console.log (This.validationerror)}
  13. }
  14. });
  15. var Contact1model = new Contactmodel ({//validate seeded data
  16. FirstName: "jo234 hn", LastName: "ao321--e", Phone: "111-1111-111111"
  17. });

Note that theisValid () method returns a useful Boolean function that shows whether the schema is valid.

Tips:

    • Save () and set () use validation functions internally.


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.