Home >Web Front-end >JS Tutorial >Detailed explanation of the model Model and its collection in the Backbone.js framework_Basic knowledge
What is Model
The author of Backbone defines Model like this:
Model is the core of any web application, it contains interactive data and most of the logic. For example: conversion, verification, attributes and access rights, etc.
So, let’s 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, and after instantiation, we get person. Any time you instantiate a Model, the initialize() method is automatically triggered (this principle also applies to collections and views). Of course, it is not mandatory to use the initialize() method when defining a Model, but as you use Backbone, you will find that it is indispensable.
Set Model properties
Now we want to pass some parameters to set the properties of the Model when creating the Model instance:
Person = Backbone.Model.extend({ initialize: function(){ alert("Welcome to Backbone!"); } }); //在实例化 Model 时直接设置 var person = new Person({ name: "StephenLee", age: 22 }); //我们也可以在 Model 实例化后,通过 set() 方法进行设置 var person = new Person(); person.set({ name: "StephenLee", age: 22});
Get Model attributes
Using the get() method of Model, we can get the properties:
Person = Backbone.Model.extend({ initialize: function(){ alert("Welcome to Backbone!"); } }); var person = new Person({ name: "StephenLee", age: 22}); var age = person.get("age"); // 22 var name = person.get("name"); // "StephenLee"
Set Model default properties
Sometimes you want the Model to contain some default attribute values when it is instantiated. 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: "StephenLee"}); var age = person.get("age"); // 因为实例化时未指定 age 值,则为默认值 30 var name = person.get("name"); //实例化制定了 name 值,则为 "StephenLee"
Use Model attributes
You can customize methods in the Model to use the properties in the Model. (All custom methods are public by default)
Person = Backbone.Model.extend({ defaults: { name: "LebronJames", age: 30, hobby: "basketball" }, initialize: function(){ alert("Welcome to Backbone!"); }, like: function( hobbyName ){ this.set({ hobby: hobbyName }); }, }); var person = new Person({ name: "StephenLee", age: 22}); person.like("coding");// 设置 StephenLee's hobby 为 coding var hobby = person.get("hobby"); // "coding"
Listen to changes in Model properties
According to Backbone's mechanism, we can monitor any attribute of the Model. Next, we try to bind an attribute of the Model in the initialize() method to monitor, taking the attribute name 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 above code, we know how to monitor a certain attribute of the Model. Suppose we need to monitor all properties of the Model, then use 'this.on("change", function(model){}); .
Data interaction between server and Model
As mentioned in the previous article, Model contains interactive data, so one of its functions is to carry data from the server and interact with the server. Now we assume that there is a mysql table user on the server side. The table has three fields id, name, and email. The server side uses REST style to communicate with the front end, using URL: /user to interact. Our Model is defined as:
var UserModel = Backbone.Model.extend({ urlRoot: '/user', defaults: { name: '', email: '' } });
Create a Model
Each Model in Backbone has an attribute id, which corresponds to the server-side data one-to-one. If we want to add a new record to the mysql table user on the server side, we only need to instantiate a Model and then call the save() method. At this time, the attribute id of the Model instance is empty, which means that the Model is newly created, so Backbone will send a POST request to the specified URL.
var UserModel = Backbone.Model.extend({ urlRoot: '/user', defaults: { name: '', email: '' } }); var user = new Usermodel(); //注意,我们并没有在此定义 id 属性 var userDetails = { name: 'StephenLee', email: 'stephen.lee@mencoplatform.com' }; //因为 model 没有 id 属性,所以此时使用 save() 方法,Backbone 会向服务器端发送一个 POST 请求,服务器端收到数据后,将其存储,并返回包含 id 的信息给 Model user.save(userDetails, { success: function (user) { alert(user.toJSON()); } })
At this time, there is an additional record with name StephenLee and email stephen.lee@mencoplatform.com in the user table of mysql on the server side.
Get a Model
We have just created a Model and stored it in the server-side database. Assume that when creating the Model, the id attribute value returned by the server is 1. At this time, we can use the id value to store the Data retrieval. When we initialize a Model instance with the id attribute value, Backbone will send a GET request to the specified URL through the fetch() operation.
var user = new Usermodel({id: 1});//初始化时指定 id 的值 //利用 fetch() 方法将会向 user/1 请求数据,服务器端将会返回完整的 user 记录,包含 name,email 等信息 user.fetch({ success: function (user) { alert(user.toJSON()); } })
Update a Model
If we need to modify the stored user record 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: 'StephenLee', email: 'stephen.lee@mencoplatform.com' });//实例化时指定 id 值 //因为指定了 id 值,此时使用 save() 方法,Backbone 将会向 user/1 发送 PUT 请求,将会对数据库中 id 为1的记录的 email 修改 user.save({email: 'newemail@qq.com'}, { success: function (model) { alert(user.toJSON()); } });
Delete a Model
If we need to delete records in the database, use the destroy() method using the known id value. At this point, Backbone will send a DELETE operation to the specified URL.
var user = new Usermodel({ id: 1, name: 'StephenLee', email: 'stephen.lee@mencoplatform.com' });//实例化时指定 id 值 //因为指定了 id 值,此时使用 destroy() 方法,Backbone 将会向 user/1 发送 DELETE 请求,服务器端接收请求后,将会在数据库中删除 id 为 1的数据 user.destroy({ success: function () { alert('Destroyed'); } });
What is Collection
In short, Collection in Backbone is an ordered collection of Models. For example, it may be used in the following situations:
Model: Student, Collection: ClassStudents Model: Todo Item, Collection: Todo List Model: Animal, Collection: Zoo
Collection generally only uses the same type of Model, but Model can belong to different types of Collection, such as:
Model: Student, Collection: Gym Class Model: Student, Collection: Art Class Model: Student, Collection: English Class
Create a Collection
//定义 Model Song var Song = Backbone.Model.extend({ defaults: { name: "Not specified", artist: "Not specified" }, initialize: function(){ console.log("Music is the answer"); } }); //定义 Collection Album var Album = Backbone.Collection.extend({ model: Song //指定 Collection 内的 Model 为 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 ); // 输出为 [song1, song2, song3]