What is Backbone.js

Source: Internet
Author: User
Tags http post

Backbone.js is a model-view-Controller (MVC) framework in a JavaScript environment. Any developer who touches a larger project must be distressed by trivial event callback logic and pyramid-like code. Furthermore, in traditional Web application code, it is unavoidable to include the code that displays the data in the application logic. This form of code becomes increasingly difficult to maintain when the size of the project grows larger, because any changes in the skeleton logic can affect the data display logic and vice versa.

Backbone is going to solve this problem of code coupling. It separates the respective logic by providing a control layer-the frame of the display layer, as well as the template (template). Such an MVC framework is similar to the traditional desktop program and the program framework of server-side programs.

Model

The core of the program using the backbone framework is the "model". In most cases, "model" represents an object structure stored in a database.

Backbone's design idea is to let the model serve to store, retrieve, and change data. Note that there are other MVC frameworks that are designed to have the controller responsible for changing the data. But Backbone's design idea is that the controller's role is only to handle user requests from the view layer, as well as access to the corresponding model layer. The model layer itself is responsible for obtaining data from the data source, as well as for data encapsulation.

The following example illustrates how the data model is declared and initialized in backbone.

Stooge = Backbone.Model.extend ({    defaults: {        ' name ': ' Guy Incognito ',        ' power ': ' Classified ',        ' Friends ': [],    },    initialize:function () {        //Do Initialization    }}); var account = new Stooge ({    name: ' Larry ',    Power: ' Baldness ',    friends: [' Curly ', ' Moe ']});

In Backbone, to create a model, you can extend the Backbone.model and provide the properties of the instance. In the above example, the Extend function creates a prototype chain for the Stooge class, so you can access all the properties in the model by stooge. And because extend correctly sets up the prototype chain, subclasses created by extend (subclasses) can also be extended in depth. Extend is an important concept in backbone, where the Extend function is used to process copying from one object to another in most JavaScript libraries. In backbone, the Extend function also creates a constructor, so you can initialize a class and then copy it to a new class to achieve a multi-tier extension.

Views View

The view represents a way to present data on a "model" basis. Depending on the logic context of the application, the view determines how the data is presented. For example, in Canada, a citizen may choose to use a short-form birth certificate or a longer-form birth certificate. Both birth certificate documents include the same key information (Model), but with varying degrees of detail (View). In backbone, the view provides a "window" to view the data in a model, assist in monitoring user interactions on the interface, or changes in the data model, triggering updates to the data display.

The following is an example of showing birth certificate data in a Web page.

<div id= "certificate" ></div>

<script type= "Text/javascript" > Certificateview = Backbone.View.extend ({ initialize:function () { This.render (); }, render:function () { $ (this.el). HTML ("

In the preceding code, a Certificateview class is declared as a view instance of the birth certificate. It also uses the backbone extend method to extend a custom view structure, which is the structure of the birth certificate (using the Extend method is the same as the extended "model" in the previous section). This custom view contains two methods:

Initialize Method-This method is executed when an instance of the view structure is created. In the code example above, the initialize to do is to immediately trigger the render function to handle the data display.

Render Method-Adjusts the contents of the DOM node to achieve the purpose of displaying the data.

In backbone, all "views" are inevitably dealt with by Dom tree manipulation. In the above code, when we instantiate the view, we pass in a DOM node that needs to display the data. If you do not pass in any DOM nodes, then backbone will process all DIV nodes on the page.

Views Template View Templates

The code in the previous section has a potential problem: the logic of generating HTML code appears in JavaScript code. Therefore, we need to use the "view template" to separate the coupling processing logic. Note that the view in backbone does not contain the template itself, it provides only the control logic of the view, and the ability to generate the template is implemented by its dependent library underscore. Template () method.

Specifically, we moved the HTML-generated logic from the render function in the view layer and placed it under a <script> tag. To prevent the browser from treating it as a real JavaScript code, the Type property of,<script> is set to Text/template (not the default text/javascript). If you do not re-declare the default type attribute, then the browser will use the JS engine to process the content, and because the view template is often an HTML code snippet, so often throw JS statement parsing error.

<div id= "certificate" ></div>
<script type= "Text/template" id= "Tpl-certificate" > < h1 > <%= name%> <script type= "Text/javascript" > Certificateview = Backbone.View.extend ({ Template: _.template ($ (' # Tpl-certificate '). html ()), initialize:function () { this.render (); }, render:function () { var Templateargs = { name: "Guy Incognito", DOB: "March 2, 1967" }; $ (this.el). HTML (this.template (Templateargs)); } ); var certificate_view = new Certificateview ({ el: $ ("#certificate") });</script>

In the preceding code, name and date are used as parameter variables for the view template. When you use variables in a template, you need to add <% and%> tags. If you need to output a variable, you need to use the <%= tag, just like the JSP syntax.

Using a template in a view requires two steps: The first step is that the view logic must know which template to use to render the data, and the second step is to pass in the variable arguments when using the template.

We used the. HTML () function of jquery to get the template content under the <script> tab. We then used the underscore. Template () function to combine the resulting HTML code based on the parameter variables and the original text of the template.

Now, using the instance name. Render () will enable the data display to work. In the render function, the parameter variables that need to be passed in to the template are first known (in most cases, this needs to be obtained from the model layer), then the HTML code is generated using the template function, and finally the contents of the DOM node are changed using Jquery.html ().

Set Collection

In backbone, a collection is an ordered combination of model models, and we can bind a "change" event to the set, which is notified when the model in the collection changes, and the collection can listen for "add" and "remove" events from the server. You can also use the methods provided by underscore (such as ForEach, filter, SortBy, and so on).

You can create a collection by extending backbone.collection.

var Library = Backbone.Collection.extend ({  model:book});

Why use collections instead of JavaScript built-in arrays, although using collections has overhead? First, creating objects in a way that extends Backbone.collection facilitates "documenting" your code. For example, in the following example, the collection class Team defines stooge as its data model type, so when you write the code, you know what kind of data type structure backbone will be working on when it processes the collection. Of course, the more important reason for using collections is that the collection provides a powerful set of commands to get/manipulate the content inside, so you don't have to write the corresponding method yourself.

var stooge = Backbone.Model.extend ({    defaults: {        ' name ': ', '        power ': '    }} '); var Team = BackBone.Collection.extend ({    model:stooge}); var Larry = new Stooge ({    name: ' Larry ',    Power: ' baldness '});  var moe = new Stooge ({    name: ' Moe ',    power: ' All Powers '}), var curly = new Stooge ({    name: ' Curly ',    power: ' Hair '); var threestooges = new Team ([Larry, Curly, Moe]);

When data changes occur in the model contained in the collection, the collection fires the corresponding event, so you can capture those events to complete the update on the view.

Synchronize Sync
In Backbone, use the Sync class (Backbone.sync) to complete the reading and storage of the data model with the server side. Typically, you can use jquery's. Ajax method to send and receive data in JSON format. If you want to use a different persistence scheme, such as WebSockets, XML, or Local Storage, we can overload the function.

Backbone.sync's syntax is sync (method, model, [optional callback]).

The Method–crud method ("Create", "read", "Update", or "delete") create corresponds to the post,read corresponding to get.
model– the model to be saved (or the collection to be read)

The most common method to use with Sync is model.save ([Attributes], [options]). Model.save saves the data model to the server side by delegating backbone.sync. The Attributes hash list (in set) should contain the properties that you want to change, and the keys not involved will not be modified. If the model contains a validate method and the validation fails, the model is not saved. If the model does not exist on the server side, save will take the "create" (HTTP POST) method, and if the model already exists on the server, the save will take the "Update" (HTTP PUT) method.

In the following example, we generate a data model of a book on the client side and sync it to the server side.

Backbone.sync = function (method, model) {    Alert (method + ":" + json.stringify (model));    Model.id = 1;}; var book = new Backbone.model ({    title: "The Rough Riders",    Author: "Theodore Roosevelt"}); Book.save (); Because the model is not on the server side, this call, Sync uses "create" request Book.save ({    Author: "Teddy"}); this time the server side is there, so sync uses "update" request. Note that this only updates the partial properties of the model. Properties that are not involved are not modified on the server side.

Routing Router

Web applications often need URLs that can be linked, collectible, and shareable for important locations in the app. More and more Web applications are starting to use anchor (hash) fragments (#page) to provide this collectible, shareable link. Along with the advent of the history API, the anchor point can already be used to process standard URLs (/page). Backbone.router provides a number of methods for client-side routing and can connect to the specified actions (actions) and events. For older browsers that do not support the history API, routing provides graceful callback functions and allows for transparent conversion of URL fragments.

It seems that the controller type is missing in the Backbone, in fact, each "route" can be seen as extending from the controller. The traditional controller is problematic because it incorporates two functions, the first is to control the Model according to the view, and the second is to control the user to switch between different view. Backbone separated the user interface and manipulated the model gracefully by separating the Router separately.

So why not set up a separate class for the controller? According to the MVC definition, the controller class should be the implementation of your program skeleton logic. In backbone, because the specific processing details of the program are separated from the controller layer (such as processing data within the model, handled by the router user request, etc.), you do not need a separate controller class to handle the skeleton logic of the program.

The following example shows how to set up a route that needs to handle URLs such as #/certificates/123 or #/certificates/mycertificatename, The route then creates a new View (new Certificateview) based on Certificateid or Certificatename. The following simple code does not handle Certificateview by ID, but in real development you may need to read/process the model by ID.

var myrouter = Backbone.Router.extend ({    routes: {        "/certificates/:id": "GetCertificate",    },    Getcertificate:function (ID) {        new Certificateview ({            el: $ ("#certificate")        });    var router = new Myrouter; Backbone.history.start ();

Resources:

Backbone Chinese Document http://www.csser.com/tools/backbone/

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.