Examples of Model and Collection in the Backbone. js framework, backbonecollection

Source: Internet
Author: User

Examples of Model and Collection in the Backbone. js framework, backbonecollection

Model
The most basic thing about backbone is model, which is like the database ing model in backend development. It is also a data object model, and it should have the same attributes as the backend model (only the attributes that need to be operated through the frontend ).
Next, let's take you through the example step by step to understand what the backbone model is like.
First, define an html page:

<! DOCTYPE html> 

The following code needs to be filled in the function in the html script tag.

1. The simplest object

Man = Backbone.Model.extend({    initialize: function(){      alert('Hey, you create me!');    }  });var man = new Man;

This is simple. In helloworld, a model is displayed, and attributes are not defined. Here is an initialization method, or a constructor.

2. Two Methods for assigning values to objects
First, define 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 '));

Second, defined when values are assigned

Man = Backbone.Model.extend({  initialize: function(){    alert('Hey, you create me!');  }});man.set({name:'the5fire',age:'10'});alert(man.get('name'));

Get is used for the value.

3. Methods in objects

Man = Backbone. Model. extend ({initialize: function () {alert ('Hey, you create me! ') ;}, Defaults: {name: 'zhang san', age: '38'}, aboutMe: function () {return 'My name' + this. get ('name') + ', this year' + this. get ('age') + 'age' ;}}); var man = new Man; alert (man. aboutMe ());

4. attributes of the listener object

Man = Backbone. Model. extend ({initialize: function () {alert ('Hey, you create me! '); // Bind to listen to this during initialization. bind ("change: name", function () {var name = this. get ("name"); alert ("You changed the name attribute to:" + name);}) ;}, ults: {name: 'zhang san', age: '38'}, aboutMe: function () {return 'My name '+ this. get ('name') + ', this year' + this. get ('age') + 'age' ;}}); var man = new Man; man. set ({name: 'the5fire'}) // triggers the bound change event, alert.

5. Add verification rules for objects and error messages

Man = Backbone. Model. extend ({initialize: function () {alert ('Hey, you create me! '); // Bind to listen to this during initialization. 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 blank! ";}}, AboutMe: function () {return 'My name '+ this. get ('name') + ', this year' + this. get ('age') + 'age' ;}}); var man = new Man; man. set ({name: ''}); // an error message is displayed based on the verification rules.

6. Obtaining and saving objects requires support from the server to be tested.
First, define a url attribute for the object. When the save method is called, all attributes of the object will be post to the server.

Man = Backbone. Model. extend ({url: '/save/', initialize: function () {alert ('Hey, you create me! '); // Bind to listen to this during initialization. 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 blank! ";}}, AboutMe: function () {return 'My name '+ this. get ('name') + ', this year' + this. get ('age') + 'age' ;}}); var man = new Man; man. set ({name: 'the5fire'}); man. save (); // a POST is sent to the url corresponding to the model. The data format is json {"name": "the5fire", "age ": 38} // then the method for obtaining data from the server is fetch ([options]) var man1 = new Man; // In the first case, if you directly use the fetch method, then he will send a get request to your model url. // you can perform the corresponding operation on the server side by determining whether it is get or post. Man1.fetch (); // In the second case, add the following parameter to fetch: man1.fetch ({url: '/getmans/'}); // in this case, the get request will be sent to the/getmans/url. // The result style returned by the server should be the corresponding json format data, the same as the previous format of POST when saving. // However, the method for receiving data returned by the server is as follows: man1.fetch ({url: '/getmans/', success: function (model, response) {alert ('success '); // The model is the obtained data alert (model. get ('name') ;}, error: function () {// when the returned format is incorrect or it is not json data, will execute this method alert ('error ');}});

Note: The above code is only executable, but the server-side instances will be available later.
Here, we need to add that Asynchronous Server operations are performed through Backbone. when this method is called, a parameter is automatically passed and the corresponding request is sent to the server based on the parameter. For example, if you save, backbone will judge whether your object is new. If it is newly created, the parameter will be "create". If it is an existing object, it will only be changed, the parameter is update. If you call the fetch method, the parameter is read. If it is destory, 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, DELETE. You can perform CRUD operations on the server based on the request type.

Note:
For url and urlRoot, if you set the url, your CRUD will send the corresponding request to this url, but another problem is that the delete request sent the request, but you didn't send any data, so you don't know which object (record) to delete on the server side. So here is another urlRoot concept. After you set urlRoot, when you send a PUT or DELETE request, the request url is/baseurl/[model. id], so that you can update or delete the corresponding object (record) on the server side by extracting and updating the post-par value of the url ).

Collection
Collection is an ordered set of model objects. It is easy to understand the concept. It is easier to look at several examples.
1. Example of book and bookshelf

Book = Backbone. model. extend ({defaults: {// thanks for the blue power correction. Changed 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 this is an array, alternatively, use addvar bookShelf = new BookShelf; bookShelf. add (book1); bookShelf. add (book2); bookShelf. add (book3); bookShelf. remove (book3); // Based on the js library underscore, you can also use the each method to obtain the data bookShelf in the collection. each (function (book) {alert (book. get ('title '));});

Simple, not explained
2. Use fetch to obtain data from the server
First, define the url in the Bookshelf above. Note that the url root attribute is not found in the collection. Or you can define the url value 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');}});

Two methods to accept the returned value are also defined. I think it is easy to understand the specific meaning. When the data in the correct format is returned, the success method is called, and the error method is called for the data in the error format, of course, the error method also depends on adding the same parameters as the success method.
The returned format of the corresponding BookShelf is as follows: [{'title': 'book1'}, {'title': 'book2'} ......]
3. reset Method
This method must be used with the above fetch. After fetch is sent to the data, the collection will call the reset method. Therefore, you need to define the reset method in the collection or bind the reset method. Here, the binding demonstration is used:

BookShelf. bind ('reset', showAllBooks); showAllBooks = function () {bookShelf. each (function (book) {// render book data to the page .});}

The binding process must be performed before fetch.
The complete collection code is provided below, which must be supported by the server. The server will be written later.

<! DOCTYPE html> 

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.