Details about the Model and collection in the Backbone. js framework

Source: Internet
Author: User
This article mainly introduces the Model and its collection in the Backbone. js framework. Backbone has a Model and View structure similar to the traditional MVC Framework. For more information, see What is Model?
The author of Backbone defines the Model as follows:

Model is the core of any web application. It contains interactive data and most of the logic. For example, conversion, verification, attributes, and access permissions.
First, create a Model:

Person = Backbone.Model.extend({  initialize: function(){    alert("Welcome to Backbone!");  }});var person = new Person;

In the above Code, we define a Model named Person. after instantiation, we can get the person. Whenever you instantiate a Model, the initialize () method is automatically triggered (this principle applies to collection and view ). Of course, defining a Model does not require the initialize () method, but with your use of Backbone, you will find it indispensable.

Set Model attributes
Now we want to pass some parameters when creating a Model instance to set the attributes of the Model:

Person = Backbone. Model. extend ({initialize: function () {alert ("Welcome to Backbone! ") ;}}); // Directly set var person = new Person ({name:" Stephen Lee ", age: 22}) when instantiating the Model }); // We can also set var person = new Person (); person through the set () method after Model instantiation. set ({name: "Stephen Lee", age: 22 });

Get Model attributes
Using the get () method of Model, we can obtain the attributes:

Person = Backbone.Model.extend({  initialize: function(){    alert("Welcome to Backbone!");  }});var person = new Person({ name: "StephenLee", age: 22});var age = person.get("age"); // 22var name = person.get("name"); // "StephenLee"

Set default properties of Model
Sometimes you want the Model to contain some default attribute values when instantiating it. This can be achieved by defining the defaults attribute of the Model:

Person = Backbone. Model. extend ({defaults: {name: "LebronJames", age: 30,}, initialize: function () {alert ("Welcome to Backbone! ") ;}}); Var person = new Person ({name:" Stephen Lee "}); var age = person. get ("age"); // because the age value is not specified during instantiation, the default value is 30var name = person. get ("name"); // specifies the name value for instantiation, which is "Stephen Lee"

Use Model attributes
You can customize methods in the Model to use the attributes in the Model. (All custom methods are public by default)

Person = Backbone. model. extend ({defaults: {name: "LebronJames", age: 30, holobby: "basketball"}, initialize: function () {alert ("Welcome to Backbone! ") ;}, Like: function (hobbyName) {this. set ({holobby: hobbyName}) ;},}); var person = new Person ({name: "Stephen Lee", age: 22}); person. like ("coding"); // set stevenlee's Hoby to codingvar Hoby = person. get ("holobby"); // "coding"

Listen for changes to the Model attribute
According to the Backbone mechanism, we can listen to any attribute of the Model. Next, we try to bind an attribute of the Model to the initialize () method for listening. The attribute name is used as an example:

Person = Backbone.Model.extend({  defaults: {    name: "LebronJames",    age: 30,  },  initialize: function(){    alert("Welcome to Backbone!");    this.on("change:name", function(model){      var name = model.get("name"); // 'KobeBryant'      alert("Changed my name to " + name );    });  }});var person = new Person();var age = person.set({name : "KobeBryant"});

Through the code above, we know how to listen to a certain attribute of the Model. Suppose we need to listen on all the attributes of the Model, use 'this. on ("change", function (model ){});.

Data Interaction Between the server and the Model
As mentioned earlier, Model contains interactive data, so one of its functions is to carry data sent from the server and interact with the server. Now we assume that the server has a mysql table user, which has three fields: id, name, and email. The server uses the REST style to communicate with the front-end and uses URL:/user for interaction. Our Model is defined:

var UserModel = Backbone.Model.extend({  urlRoot: '/user',  defaults: {    name: '',    email: ''  }});

Create a Model
Each Model in Backbone has an attribute id that corresponds to the server-side data. If we want to add a record to the mysql table user on the server side, we only need to instantiate a Model and call the save () method. In this case, the property id of the Model instance is null, indicating that the Model is created. Therefore, Backbone will send a POST request to the specified URL.

Var UserModel = Backbone. model. extend ({urlRoot: '/user', ults: {name: '', email:''}); var user = new Usermodel (); // note, we have not defined the id attribute var userDetails = {name: 'filename', email: 'Stephen. lee@mencoplatform.com '}; // because the model does not have the id attribute, so using the save () method at this time, Backbone will send a POST request to the server, the server receives the data, store it, and return the information containing the id to Modeluser. save (userDetails, {success: function (user) {alert (user. toJSON ());}})

At this point, in the user table of the server-side mysql, a record with name as Stephen Lee and email as stephen.lee@mencoplatform.com is added.

Obtain a Model
We have just created a Model and stored it in the database on the server. Assume that when the Model is created, the id attribute value returned by the server is 1. At this time, we can retrieve the stored data through the id value. When we initialize a Model instance with the id attribute value, the Backbone will send a GET request to the specified URL through the fetch () operation.

Var user = new Usermodel ({id: 1}); // specify the id value during initialization // The fetch () method will request data to user/1, the server returns the complete user record, including name, email, and other information. fetch ({success: function (user) {alert (user. toJSON ());}})

Update a Model
If we need to modify the Stored user records and use the known id value, we also use the save () method, but because the id is not empty at this time, backbone will send a PUT request to the specified URL.

Var user = new Usermodel ({id: 1, name: 'filename', email: 'Stephen. lee@mencoplatform.com '}); // specify the id value when instantiating // because the id value is specified, when using the save () method, Backbone will send a PUT request to user/1, the user will be modified by email of the record with id 1 in the database. save ({email: 'newemail @ qq.com '}, {success: function (model) {alert (user. toJSON ());}});

Delete A Model
To delete records in the database, use the destroy () method using the known id value. In this case, Backbone will send a DELETE operation to the specified URL.

Var user = new Usermodel ({id: 1, name: 'filename', email: 'Stephen. lee@mencoplatform.com '}); // specify the id value when instantiating // because the id value is specified, then using the destroy () method, Backbone will send a DELETE request to user/1, after receiving the request, the server deletes the user with id 1 in the database. destroy ({success: function () {alert ('deleted ');}});

What is Collection
In short, the Collection in Backbone is an ordered set of the Model. For example, it may be used in the following scenarios:

Model: Student, Collection: ClassStudentsModel: Todo Item, Collection: Todo ListModel: Animal, Collection: Zoo

Collection generally only uses the same type of Model, but the Model can belong to different types of Collection, for example:

Model: Student, Collection: Gym ClassModel: Student, Collection: Art ClassModel: Student, Collection: English Class

Create a Collection

// Define Model Songvar Song = Backbone. model. extend ({defaults: {name: "Not specified", artist: "Not specified"}, initialize: function () {console. log ("Music is the answer") ;}}); // define Collection Albumvar Album = Backbone. collection. extend ({model: Song // specify the Model in the Collection as Song}); var song1 = new Song ({name: "How Bizarre", artist: "OMC "}); var song2 = new Song ({name: "Sexual Healing", artist: "Marvin Gaye"}); var song3 = new Song ({name: "Talk It Over In Bed ", artist: "OMC"}); var myAlbum = new Album ([song1, song2, song3]); console. log (myAlbum. models); // The output is [song1, song2, song3]

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.