What is a 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, 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 a person. Any time you instantiate a Model, the initialize() method will be automatically triggered (this principle also applies to collection, view). Of course, the initialize() method is not mandatory when defining a Model, but as you use Backbone, you will find it indispensable.
Set Model properties
Now we want to pass some parameters when creating a Model instance to set the properties of the Model:
Person = Backbone.Model.extend({ initialize: function(){ alert("Welcome to Backbone!"); }});//Set var person = new Person({ name: "StephenLee", age: 22 });//We can also set var person = new Person() after the Model is instantiated by the set() method. var person = new Person(); person.set({ name: "StephenLee", age: 22});Obtain Model properties
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"); // 22var name = person.get("name"); // "StephenLee"Set Model default properties
Sometimes you want the Model to include some default property values when instantiating it, which can be achieved by defining the defaults property 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"); // Because the age value is not specified during instantiation, the default value is 30var name = person.get("name"); // If the instantiation has set the name value, it is "StephenLee"Use Model properties
You can customize methods in the Model to use properties within the Model. (All custom methods default to public)
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");// Set StephenLee's hobby to codingvar hobby = person.get("hobby"); // "coding"Listen to the change of Model properties
According to the Backbone mechanism, we can listen for any attribute of the Model. Next, we try to bind the attribute of a Model in the initialize() method to listen for it, 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 listen for a certain property of the Model. Assuming we need to listen on all the properties of the Model, use 'this.on("change", function(model){}); .
Data interaction between server and model
As mentioned earlier, Model contains interactive data, so one of its functions is to carry data transmitted from the server and interact with the server. Now let's assume that there is a table user of mysql on the server, which has three fields id, name, and email. The server side uses REST style to communicate with the front-end and uses the 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 a property id, which corresponds to server-side data one by one. If we want to add a new record to the server-side mysql table user, we just need to instantiate a Model and 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();//Note that we do not define the id attribute here var userDetails = { name: 'StephenLee', email: '[email protected]'};//Because model does not have an id attribute, use the save() method at this time. Backbone will send a POST request to the server side. After receiving the data, the server side stores it and returns the information containing the id to Modeluser.save(userDetails, { success: function (user) { alert(user.toJSON()); }})At this time, there is an additional record in the user table of mysql on the server with name StephenLee and email [email protected].
Get a Model
We have just created a Model and stored it in the server-side database. Assuming that when creating the Model, the id attribute value returned by the server-side is 1. At this time, we can retrieve the stored data through the value of id. When we initialize a Model instance with the id attribute value, through the fetch() operation, Backbone will send a GET request to the specified URL.
var user = new Usermodel({id: 1});//Specify the value of id during initialization//Use the fetch() method to request data from user/1, and the server side will return the complete user record, including name, email and other information user.fetch({ success: function (user) { alert(user.toJSON()); }})Update a Model
If we need to modify the stored user record, use the known id value and 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: '[email protected]'});//Specify the id value when instantiating // Because the id value is specified, use the save() method at this time. Backbone will send a PUT request to user/1, and will modify the email of the record with id 1 in the database user.save({email: '[email protected]'}, { success: function (model) { alert(user.toJSON()); }});Delete a Model
If we need to delete records in the database, use the known id value and use destroy() method. At this point, Backbone will send a DELETE operation to the specified URL.
var user = new Usermodel({ id: 1, name: 'StephenLee', email: '[email protected]'});//Specify the id value when instantiating // Because the id value is specified, use the destroy() method at this time, Backbone will send a DELETE request to user/1. After receiving the request, the data with id 1 will be deleted in the database user.destroy({ success: function () { alert('Destroyed'); }});What is Collection
In short, the Collection in Backbone is an ordered collection of Models, for example, it may be used in the following situations:
Model: Student, Collection: ClassStudentsModel: Todo Item, Collection: Todo ListModel: 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 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 Collection as Song});var song1 = new Song({ name: "How Bizarre", artist: "OMC" });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]