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.
- i.e.
- New Backbone.model (
- {firstName: "John", LastName: "Doe", Phone: "1-111-1111"}
- );
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.
- var Contact1model = new Backbone.model (
- {firstName: "John", LastName: "Doe", Phone: "111-111-1111"}
- );
- var Contact2model = new Backbone.model (
- {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"}
- );
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.
- var Contactmodel = Backbone.Model.extend ({//extend Backbone.model
- Getfullname:function () {
- Return This.get ("firstName") + "" + This.get ("LastName");
- }
- });
- var Contact1model = new Contactmodel (//instantiate Contactmodel instance
- {firstName: "John", LastName: "Doe", Phone: "111-111-1111"}
- );
- var Contact2model = new Contactmodel (//instantiate Contactmodel instance
- {firstName: "Jane", LastName: "Doe", Phone: "222-222-2222"}
- );
- Call the Getfullname method on our model
- Console.log (Contact1model.getfullname ()); Logs John Doe
- Console.log (Contact2model.getfullname ()); Logs Jane Doe
Tips:
- 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"}).
- 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.
- 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.
- 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.
- var Contactmodel = Backbone.Model.extend ({//Inheritance Backbone.model
- Defaults: {
- FirstName: "No-name Yet",
- LastName: "No last Name yet"
- }
- });
- var Contact1model = new Contactmodel (//Instantiation Model Instance
- {firstName: "John"}
- );
- FirstName is set to John while keeping LastName as the default value
- Console.log (Contact1model.get ("FirstName")); Log John
- 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).
- var Contactmodel = Backbone.Model.extend ({//Inheritance Backbone.model
- Defaults:function () {
- This.firstname = "No Name yet";
- This.lastname = "No last name yet";
- return this;
- }
- });
- var Contact1model = new Contactmodel (//Instantiation Model Instance
- {firstName: "John"}
- );
- FirstName is set to John while keeping LastName default values unchanged
- Console.log (Contact1model.get ("FirstName")); Log John
- 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.
- var contact = new Backbone.model (); Instantiating a model instance
- Set up/Edit data
- Contact.set ({firstName: "John", LastName: "Doe", Phone: "1-111-1111"});
- Owning the FirstName property, notice that no matter what the value of the property will return True
- Get Data
- Console.log (Contact.get ("FirstName")); Log John
- Recover data
- Contact.unset ("LastName");
- Verify that the data has been recovered
- Console.log (Contact.has ("LastName")); Log False
- Clear All data
- Contact.clear ();
- Verify that the data has been cleared
- Console.log (contact.attributes); Log Empty {}
Tips:
- These methods should be used instead of directly editing the internal attributes objects so that the events in the model can be triggered correctly.
- set (), unset ( ) and Clear () methods can invoke internal change events.
- The set () method receives an option object (for example: set ({"Name": "Value", "Name": "Value"}), or two string parameters (for example: Set ("Name", "value")).
- set (), unset (), and Clear () methods both receive the {silent:true} option to prevent any backbone embedded event from occurring.
- 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.
- var Contact1model = new Backbone.model (//instantiate Model instance
- {firstName: "John", LastName: "Doe"}
- );
- 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.
- var Contact1model = new Backbone.model (//Instantiation Model Instance
- {firstName: "John", LastName: "Doe"}
- );
- Console.log (Contact1model.tojson ()); Log {firstname= "John", Lastname= "Doe"}
- Note that this is not a reference, but a copy of the Property object
- i.e.
- 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:
- 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.
- 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.
- var contact = new Backbone.model ({
- FirstName: "John", LastName: "Doe", Phone: "1-111-1111"
- });
- Returns the array/property key for the data
- Console.log (Contact.keys ()); Log ["FirstName", "LastName", "phone"]
- Returns the array/property value of the data
- Console.log (Contact.values ()); Log ["John", "Doe", "1-111-1111"]
- Copy the Data/Property object, returning the object containing the selected key
- Console.log (Contact.pick ("Phone")); Log {phone= "1-111-1111"}
- Copy a data/Property object, returning an object that does not contain a selected key
- 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.
- var contact= New Backbone.model ();
-  
- var Contactview = Backbone.View.extend ({
- Initialize:function () {
- This.listento (contacts," Change ", This.render); Listen to change event on model
-
- Render:function () {
- Console.log (" data changed, Re-render ");
- }
- });
-  
- new Contactview ();
-  
- contact.set ({//This will trigger the Change event
- FirstName: "John", LastName: "Doe", Phone: " 111-111-1111 "
- });
-  
- 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.
- var contact= new Backbone.model ();
- var Contactview = Backbone.View.extend ({
- Initialize:function () {
- Listen for change events on the model
- This.listento (Contact, "Change:firstname", This.render);
- },
- Render:function () {Console.log ("Render a change, data changed");}
- });
- New Contactview ();
- The Change event is activated because we only monitor FirstName
- 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.
- Create a contact model, and no change event is activated when the model is instantiated with data
- var contact=new backbone.model ({firstName: "John", LastName: "Doe", Phone: "1-111-1111"});
- Make a change
- Contact.set ({phone: "2-222-2222"});
- Verify that a change has occurred
- Console.log (contact.haschanged ()); Logs true
- Get properties that have been changed
- 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.
- Create a contact model, and no change event is activated when the model is instantiated with data
- var contact=new backbone.model ({firstName: "John", LastName: "Doe", Phone: "111-111-1111"});
- Make a change
- Contact.set ({phone: "2-222-2222", FirstName: "Jane"});
- Get the initial value of the phone number
- Console.log (contact.previous ("Phone")); Log 111-111-1111
- To get all the property states before the last Change event
- 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 ().
- var contact = New Backbone.model ({
- FirstName: "John", LastName: "Doe", phone:0
-
-  
- contact.validate = function (attributes,options) {
- var Validphone =/\ (? \d{3}\w?\s? \d{3}\w?\d{4}/.test (Attributes.phone);
- if (!validphone) {
- returns "Setting or saving Invalid Phone number attempted";
- }
-
-  
- contact.set ("Phone", "111-1 11-1111 ", {validate:true}); Set
- contact.set ("Phone", "111-1-1111", {validate:true});//no set, validation failed
-
- console.log (Contact.get ("Phone"));//No Invalid phone number
- 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:
- 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.
- 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.
- var contact = new Backbone.model ({firstName: "John", LastName: "Doe"});
- Contact.validate = function (attributes,options) {
- if (!validphone) {returns "Setting or saving Invalid Phone number attempted";}
- };
- Backbone to listen for invalid events on the contact model
- Backbone.listento (Contact, "Invalid", function (model,error,options) {
- Console.log (model,error,options);
- });
- Set invalid phone number trigger invalid event
- 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.
- var Contactmodel = Backbone.Model.extend ({//extend Backbone.model
- Validate:function (attributes,options) {
- var phone =/\ (\d{3}\w?\s?\d{3}\w?\d{4}/.test (Attributes.phone);
- var firstName =/^[a-z] "? [A-za-z]+ (-[a-za-z]+) $/.test (attributes.firstname);
- var lastName =/^[a-z] "? [A-za-z]+ (-[a-za-z]+) $/.test (attributes.lastname);
- if (!phone!firstname!lastname) {
- Return "Setting, saving, or seeding Invalid Data"
- }
- },
- Initialize:function () {
- Run validation, if invalid will output information
- if (!this.isvalid ()) {Console.log (This.validationerror)}
- }
- });
- var Contact1model = new Contactmodel ({//validate seeded data
- FirstName: "jo234 hn", LastName: "ao321--e", Phone: "111-1111-111111"
- });
Note that theisValid () method returns a useful Boolean function that shows whether the schema is valid.
Tips:
- Save () and set () use validation functions internally.