Model
Regarding backbone, the most basic thing is model. This thing is like the database mapping model in back-end development. It is also a model of data objects, and it should have the same attributes as the model in the back-end (only attributes that need to be operated through the front-end).
Let’s take a look at what the backbone model is from the example step by step.
First define an html page:
<!DOCTYPE html><html><head><title>the5fire-backbone-model</title></head><body></body><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script><script>(function ($) {/** *Putting code here**/})(jQuery);</script></html>The following code needs to be filled in the function in the script tag of this html.
1. The simplest object
Man = Backbone.Model.extend({ initialize: function(){ alert('Hey, you create me!'); } });var man = new Man;This is very simple. There is also a model presentation in helloworld, without defining attributes. This is a method during initialization, or a constructor.
2. Two methods of object assignment
The first one is to define directly and set the default value.
Man = Backbone.Model.extend({ initialize: function(){ alert('Hey, you create me!'); }, defaults: { name:'Zhang San', age: '38' }});var man = new Man;alert(man.get('name'));The second type is defined when assigning
Man = Backbone.Model.extend({ initialize: function(){ alert('Hey, you create me!'); }});man.set({name:'the5fire',age:'10'});alert(man.get('name'));When using get values, get is used.
3. Methods in the object
Man = Backbone.Model.extend({ initialize: function(){ alert('Hey, you create me!'); }, defaults: { name:'Zhang San', age: '38' }, aboutMe: function(){ return 'My name is' + this.get('name') + ', this year' + this.get('age') + 'year-old'; }});var man = new Man;alert(man.aboutMe());4. Listen to the changes in attributes in the object
Man = Backbone.Model.extend({ initialize: function(){ alert('Hey, you create me!'); //Bind listening during initialization this.bind("change:name",function(){ var name = this.get("name"); alert("You changed the name attribute to: " + name); }); }, defaults: { name:'Zhang San', age: '38' }, aboutMe: function(){ return 'My name is' + this.get('name') + ', this year' + this.get('age') + 'year'; }}); var man = new Man;man.set({name:'the5fire'}) //Trigger the bound change event, alert.5. Add verification rules to the object and error prompts
Man = Backbone.Model.extend({ initialize: function(){ alert('Hey, you create me!'); //Bind listening during initialization this.bind("change:name",function(){ var name = this.get("name"); alert("You changed the name attribute to: " + name); }); this.bind("error",function(model,error){ alert(error); }); }, defaults: { name:'Zhang San', age: '38' }, validate:function(attributes){ if(attributes.name == '') { return "name cannot be empty!"; } }, aboutMe: function(){ return 'My name is' + this.get('name') + ',This year' + this.get('age') + 'year-old'; }});var man = new Man;man.set({name:''}); //According to the verification rules, an error message pops up.6. The acquisition and storage of objects require server-side support to be tested.
First, you need to define a url attribute for the object. When calling the save method, all attributes of the object will be posted to the server.
Man = Backbone.Model.extend({ url:'/save/', initialize: function(){ alert('Hey, you create me!'); //Bind listening during initialization this.bind("change:name",function(){ var name = this.get("name"); alert("You changed the name attribute to: " + name); }); this.bind("error",function(model,error){ alert(error); }); }, defaults: { name:'Zhang San', age: '38' }, validate:function(attributes){ if(attributes.name == '') { return "name cannot be empty!"; } }, aboutMe: function(){ return 'My name is' + this.get('name') + ',This year' + this.get('age') + 'year-old'; }});var man = new Man;;man.set({name:'the5fire'});man.save(); //The POST will be sent to the url corresponding to the model, and the data format is json{"name":"the5fire","age":38}//Then then get the data from the server side using method fetch([options])var man1 = new Man;//In the first case, if the fetch method is used directly, it will send a get request to the url of your model, //You can perform corresponding operations by determining whether it is get or post on the server side. man1.fetch();//In the second case, add parameters to fetch, as follows: man1.fetch({url:'/getmans/'}); //In this way, a get request will be sent to the url /getmans/. //The result style returned by the server should be the corresponding json format data, the same as the format of POST when saving. //However, the method of accepting the data returned by the server is as follows: man1.fetch({url:'/getmans/',success:function(model,response){ alert('success'); //model is the retrieved data alert(model.get('name')); },error:function(){ //When the return format is incorrect or non-json data, this method will be executed alert('error'); }});Note: The above codes are only codes that can be executed normally, but there will be instances about the server side later.
It should be added here that the asynchronous operation of the server is completed through the Backbone.sync method. When calling this method, a parameter will be automatically passed and the corresponding request will be sent to the server according to the parameters. For example, if you save and backbone will determine whether your object is new. If it is newly created, the parameter is create. If it is an existing object, it has only been changed, then the parameter is update. If you call the fetch method, the parameter is read. If it is destory, then the parameter is delete. That is, the so-called CRUD ("create", "read", "update", or "delete"), and the request types corresponding to these four parameters are POST, GET, PUT, and DELETE. You can make corresponding CRUD operations on the server based on this request type.
Note:
Regarding url and urlRoot, if you set url, your CRUD will send the corresponding request to this url. However, another problem is that the delete request is sent, but no data is sent. Then you don’t know which object (record) should be deleted on the server side. So here is another concept of urlRoot. After you set urlRoot, when you send PUT and DELETE requests, the url address of the request is: /baseurl/[model.id], so you can update or delete the corresponding object (record) by extracting the values after url on the server side.
Collection
Collection is an ordered collection of model objects. It is very simple to understand the concept. If you look at it through a few examples, you will find it simpler.
1. Examples about books and bookshelf
Book = Backbone.Model.extend({defaults: { // Thanks to netizens for changing the blue power correction to defaultstitle:'default'},initialize: function(){//alert('Hey, you create me!');}});BookShelf = Backbone.Collection.extend({model: Book});var book1 = new Book({title: 'book1'});var book2 = new Book({title: 'book2'});var book3 = new Book({title: 'book3'});//var bookShelf = new BookShelf([book1, book2, book3]); //Note that it is an array, or use addvar bookShelf = new BookShelf;bookShelf.add(book1);bookShelf.add(book2);bookShelf.add(book3);bookShelf.remove(book3);//Based on the underscore js library, you can also use each method to obtain the data in the collection bookShelf.each(function(book){alert(book.get('title'));});Very simple, no explanation
2. Use fetch to get data from the server side
First, you need to define the url in the Bookshelf above. Note that the urlRoot property does not exist in the collection. Or you directly define the value of the url in the fetch method, as follows:
bookShelf.fetch({url:'/getbooks/',success:function(collection,response){collection.each(function(book){alert(book.get('title'));});},error:function(){alert('error');}});There are also two methods that accept return values. I think it is easy to understand the specific meaning. If you return data in the correct format, you will call the success method, and the error method will be called. Of course, the error method also depends on adding the same formal parameters as the success method.
The corresponding BookShelf returns format is as follows: [{'title':'book1'},{'title':'book2'}.....]
3. Reset method
When this method is used, it must be coordinated with the above fetch. After the collection fetches the data, the reset method will be called, so you need to define the reset method or bind the reset method in the collection. Here is a demonstration of using bindings:
bookShelf.bind('reset',showAllBooks);showAllBooks = function(){bookShelf.each(function(book){ // Render the book data to the page.});}The binding steps must be performed before fetch.
The complete code about collection is given below, which requires server-side support. The server-side construction will be written later.
<!DOCTYPE html><html><head> <title>the5fire-backbone-collection</title></head><body></body><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script><script>(function ($) { //collection is an ordered collection of simple models//1. A simple example Book = Backbone.Model.extend({ defaults : { //Thanks to netizens for changing the blue power correction to defaults title:'default' }, initialize: function(){ //alert('Hey, you create me!'); } }); BookShelf = Backbone.Collection.extend({ model : Book }); var book1 = new Book({title : 'book1'}); var book2 = new Book({title : 'book2'}); var book3 = new Book({title : 'book3'}); //var bookShelf = new BookShelf([book1, book2, book3]); //Note that this is an array, or use add var bookShelf = new BookShelf; bookShelf.add(book1); bookShelf.add(book2); bookShelf.add(book3); bookShelf.remove(book3); /* for(var i=0; i<bookShelf.models.length; i++) { alert(bookShelf.models[i].get('title')); } */ // Based on the underscore js library, you can also use each method to obtain the data in the collection bookShelf.each(function(book){ alert(book.get('title')); }); //2. Use fetch to obtain data from the server side, and use reset to render bookShelf.bind('reset', showAllBooks); bookShelf.fetch({url:'/getbooks/',success:function(collection,response){ collection.each(function(book){ alert(book.get('title')); }); },error:function(){ alert('error'); }}); showAllBooks = function(){ bookShelf.each(function(book){ //Render the book data to the page. }); } //The above codes are only code that can be executed normally, but the server-side instance will be later. })(jQuery);</script></html>