The basic knowledge of model and collection in Backbone.js framework

Source: Internet
Author: User
Tags extend script tag

Model
about backbone, the most basic thing is model, this thing is like in the back-end development of the database mapping that model, but also data object models, And it should have the same properties as the back-end model (only properties that need to be manipulated by the front end).
Here is a step-by-step from the example to take you to understand the backbone model is what kind of a thing.
First, define an HTML page:

<! DOCTYPE html>
 
 

The following code needs to be filled in with the function in the script tag of this HTML.

1, one of the simplest objects

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

This is very simple, in the HelloWorld also has a model of the show, do not define attributes, here is an initialization method, or called a constructor.

2. Two methods of assigning value to objects
the first, directly defined, sets the default value.

Man = Backbone.Model.extend ({
  initialize:function () {
    alert (' Hey, create me! ');
  },
  defaults: {
    name: ' John ', Age
    : '}
  } '
;

var mans = new Man;
Alert (man.get (' name '));

Second, when assigning a value, define

Man = Backbone.Model.extend ({
  initialize:function () {
    alert (' Hey, create me! ');
  }
});
Man.set ({name: ' The5fire ', Age: ');
Alert (man.get (' name '));

When you take a value, you use Get.

3, methods in the object

Man = Backbone.Model.extend ({
  initialize:function () {
    alert (' Hey, create me! ');
  },
  defaults: {
    Name: ' John ', Age
    : ' n '
  },
  aboutme:function () {return
    ' my name ' + this.get (' name ') + ', this year ' + this.get (' age ') + ' years old ';
  }
});
var mans = new Man;
Alert (Man.aboutme ());

4, listening to the object of the changes in properties

Man = Backbone.Model.extend ({
  initialize:function () {
    alert (' Hey, create me! ');
    The binding listens
    for This.bind ("Change:name", function () {
      var name = This.get ("name") when initializing;
      Alert ("You changed the Name property to:" + name);
  },
  defaults: {
    name: ' John ', Age
    : '
  }
  ', Aboutme:function () {return
    ' my name ' + this.get (' name ') + ', this year ' + this.get (' age ') + ' year ';
  }
});
var mans = new Man;
Man.set ({name: ' The5fire '})//triggers the binding Change event, alert.

5, to add validation rules for the object, as well as error tips

Man = Backbone.Model.extend ({
  initialize:function () {
    alert (' Hey, create me! ');
    The binding listens
    for This.bind ("Change:name", function () {
      var name = This.get ("name") when initializing;
      Alert ("You changed the Name property to:" + name);
    });
    This.bind ("Error", function (model,error) {
      alert (error);
    };
  },
  defaults: {
    name: ' John ', Age
    : '
  },
  validate:function (attributes) {
    if (attributes.name = = ') {return
      ' name cannot be empty! ';
    }
  },
  aboutme:function () {return
    ' my name ' + this.get (' name ') + ', this year ' + this.get (' age ') + ' year ';
  }
});
var mans = new Man;
Man.set ({name: '} '); According to the validation rules, pop-up error prompts.

6, the acquisition and preservation of objects, the need for server-side support to test.
first you need to define a URL property for the object, and when you call the Save method, you post all the properties of the object to the server side.

Man = Backbone.Model.extend ({url: '/save/', initialize:function () {alert (' Hey, create me! ');
      The binding listens for This.bind ("Change:name", function () {var name = This.get ("name") when initializing;
    Alert ("You changed the Name property to:" + name);
    });
    This.bind ("Error", function (model,error) {alert (error);
  });
      }, Defaults: {name: ' John ', Age: '}, validate:function (attributes) {if (Attributes.name = = ') { Return ' name cannot be empty!
    ";
  }, Aboutme:function () {return ' my name ' + this.get (' name ') + ', this year ' + this.get (' age ') + ' year ';
}
});
var mans = new Man;;
Man.set ({name: ' The5fire '}); Man.save ();
The URL to post to the model is sent, the data format is json{"name": "The5fire", "Age": 38}//Then is the method of fetching data using the server side fetch ([options]) var man1 = new Man;
In the first case, if you use the Fetch method directly, he sends a GET request to the URL of your model,//You can perform the corresponding operation on the server by judging whether it is get or post.
Man1.fetch ();
  In the second case, add parameters to the fetch, as follows: Man1.fetch ({url: '/getmans/'});

In this way, the GET request is sent to the/getmans/URL, the result style returned by the server should be the corresponding JSON format data, and the format of the previous post with Save. However, the data method that accepts server-side returns is this: MAn1.fetch ({url: '/getmans/', success:function (model,response) {alert (' success ');
  Model is the data alert (model.get (' name ') that is fetched);
  },error:function () {///when the return format is incorrect or is not JSON data, this method alert (' ERROR ') is executed;

 }});

Note: The above code is only code that executes normally, but the server-side instance will be available later.
Here also add that the asynchronous operation of the server is done by Backbone.sync this method, call this method will automatically pass a parameter in the past, according to the parameters of the server to send the corresponding request. For example, you save,backbone will judge your object is not new, if the new created is the parameter is create, if the existing object is only changed, then the parameter is update, if you call the Fetch method, the argument is read, If it is destory, then the argument is delete. This is called CRUD ("create", "read", "Update", or "delete"), and these four parameters correspond to the request type Post,get,put,delete. You can make the appropriate CRUD operations on the server according to the request type.

Note:
With respect to URLs and UrlRoot, if you set up a URL, your crud will send a corresponding request to the URL, but then another problem is the delete request, the request is sent, but no data is sent. Then you do not know which object to delete on the server side (record), so here is another urlroot concept, you set the UrlRoot, when you send the put and delete request, the URL address of its request is:/baseurl/[model.id], This allows you to update or delete the corresponding object (record) on the server side by extracting the face value from the URL.

Collection
Collection is an ordered set of model objects, the concept is very simple to understand, in the case of a few examples, it will feel simpler.
1. Examples of book and bookshelf

Book = Backbone.Model.extend ({

defaults: {  //Thanks to the blue power of netizens) change

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 the add

var bookshelf = new Bookshelf;

Bookshelf.add (BOOK1);

Bookshelf.add (BOOK2);

Bookshelf.add (BOOK3);

Bookshelf.remove (BOOK3);



Based on underscore this JS library, you can also use each method to get the data

Bookshelf.each in collection (function (book) {

alert (book.get (' Title ');

});

Very simple, no explanation.
2. Use fetch to get data from server side
First, you define the URL in the bookshelf above, and note that collection does not urlroot this property. Or you define the value of the URL directly 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 ');

}});

It also defines two methods that accept the return value, which I think is easy to understand, returns the correct format of the data, will call the success method, the wrong format of the data will call the error method, of course, the error method also see Add and success method like the formal parameters.
The return format of the corresponding bookshelf is as follows: [{' title ': ' Book1 '},{' title ': ' Book2 '} ...]
3. Reset method
This method is to match the above fetch, collection will call the Reset method after the data is fetch, so you need to define the reset method in collection or bind the Reset method. Here you use the Bindings demo:

Bookshelf.bind (' Reset ', showallbooks);

Showallbooks = function () {

Bookshelf.each (function (book) {

  //) renders the book data to the page.

});

}

The steps to bind are performed before the fetch.
The following is a complete code for collection, which requires server-side support, and the server-side build 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.