What is Backbone. js?

Source: Internet
Author: User

Backbone. js is a Model-View-controller (MVC) framework in a JavaScript environment. Any developer who is familiar with large-scale projects will be troubled by the trivial Event Callback logic and pyramid-like code. In addition, in traditional Web application code, it is inevitable that the Code displaying data is added to the application logic. As the project grows, this type of code becomes increasingly difficult to maintain, because any change in the main logic may affect the data display logic, and vice versa.

Backbone is to solve the code coupling problem. It provides a control layer-display layer framework and a template to separate its own logic. Such a MVC framework is similar to a traditional desktop program and a server-side program framework.

 

Model

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

The Backbone design philosophy is to enable the model to serve the storage, acquisition, and change of data. Note that some other MVC frameworks are designed to allow controllers to change data. However, the concept of backbone is that the controller only serves to process user requests from the view layer and access the corresponding model layer. The model layer is responsible for obtaining data (from the data source) and 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 expand Backbone. Model and provide the attributes of the instance. In the preceding example, the extend function creates a prototype chain for the Stooge class. Therefore, you only need to use Stooge to access all attributes in the model. In addition, because extend correctly sets the prototype chain, the subclasses created through extend can also be extended in depth. Extend is an important concept in backbone. In most JavaScript libraries, extend functions are used to process copying from one object to another. In backbone, the extend function also creates a constructor, so you can initialize a class and copy it to the new class to achieve multi-layer extension.

 

View

A view represents a method for displaying data based on a "model. The view determines how data is displayed based on different application logic contexts. For example, in Canada, a citizen can choose to use a short-format birth certificate or a longer-format birth certificate. Both birth certificates contain the same key information (model), but the details are different (view ). In backbone, the view provides a "window" to view the data in a model, assist in listening for changes in user interaction or data models on the interface, and trigger data display updates.

The following is an example of displaying the birth certificate data on the webpage.

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

<script type="text/javascript"> CertificateView = Backbone.View.extend({ initialize: function () { this.render(); }, render: function () { $(this.el).html("

In the above Code, a certificateview class is declared as a view instance of the birth certificate. It also uses the extend method of backbone to expand a custom view structure, that is, the birth proof structure (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 this view structure is created. In the preceding code example, initialize needs to immediately trigger the render function to process data display.

Render Method -- adjust the content in the DOM node to display data.

In backbone, all "views" must inevitably deal with DOM tree operations. In the above Code, we input a DOM node to display data when instantiating the view. If you do not input any DOM nodes, backbone processes all Div nodes on the page.

 

View Template

The code in the previous section has a potential problem: the logic for generating HTML code appears in JavaScript code. Therefore, we need to use the "view template" to separate the coupled processing logic. Note: The view in backbone does not contain the template itself. It only provides the view control logic, and the specific template generation function is implemented by the. template () method in the underscore library.

Specifically, we moved the HTML generation logic from the render function at the view layer and placed it under a <SCRIPT> tag. To prevent the browser from processing it as a real JavaScript code, the type attribute of <SCRIPT> is set to text/template (instead of the default text/JavaScript ). If the default type attribute is not re-declared, the browser will use the JS engine to process the content, because the view template is often an HTML code segment, therefore, JS statement parsing errors are usually thrown.

<div id="certificate"></div>
<script type="text/template" id="tpl-certificate"> < h1 > <%= name %> < /h1> <p> DOB: <%= dob %> </p ></script>
<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 above Code, name and date are treated as parameter variables of the view template. When using variables in the template, you must add the <% and %> labels. To output variables, use the <% = tag, which is the same as the JSP syntax.

To use a template in a view, you must pay attention to the following two steps: Step 1. View logic must know which template to use to render data. Step 2: input variable parameters when using the template.

We use jquery's. html () function to obtain the template content under the <SCRIPT> tag. Then, we use the underscore. template () function to combine the parameter variables and the original template to generate the HTML code to be displayed.

Now, you can use Instance name. Render () to display data. In the render function, first declare the parameter variables that need to be passed in the template (in most cases, this needs to be obtained from the model layer), then use the template function to generate HTML code, and finally use jquery.html () modify the content in the DOM node.

 

Collection

In backbone, a set is an ordered combination of model models. We can bind a "change" event to the set to receive notifications when the model in the Set changes, the collection can also listen to "add" and "Remove" events and update from the server. You can also use the methods provided by underscore (for example, foreach, filter, sortby ).

You can create a collection by extending backbone. collection.

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

Despite the overhead of using collections, why do we need to use collections instead of JavaScript built-in arrays? First, by extending Backbone. Collection to create objects, You can "document" your code. For example, in the following example, the Collection class Team defines Stooge as its data model type, so when you write code, you will know what data type structure does backbone follow when processing the set. Of course, the more important reason for using a set is that the Set provides a set of powerful commands for you to obtain/manipulate the content, so you do not need to write the corresponding method by 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 the data of the "model" contained in the Set changes, the set will trigger corresponding events. Therefore, you can capture those events to update the view.

 

Sync
In backbone, use the Sync class (Backbone. sync) to read and store data models on the server. In general, you can use jQuery's. ajax method to send and receive data in JSON format. To use different persistence schemes, such as WebSockets, XML, or Local Storage, we can reload this function.

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

Method-CRUD method ("create", "read", "update", or "delete") create corresponds to POST and read corresponds to GET.
Model-model to be saved (or set to be read)

The most common method used with sync is model. Save ([attributes], [Options]). Model. Save saves the data model to the server by entrusting backbone. Sync. The attributes Hash (in set) should contain the attributes to be changed. Keys not involved will not be modified. If the model contains the validate method and verification fails, the model is not saved. If the model does not exist on the server side, save uses the "Create" (http post) method. If the model already exists on the server, save uses the "Update" (http put) method.

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

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 does not exist on the server side, sync will use "CREATE" to request book this time. save ({Author: "Teddy"}); this time the server has, so sync uses the "Update" request. Note that only some attributes of the model are updated. Properties not involved are not modified on the server.

 

Router

Web applications usually need URLs that can be linked, added to favorites, and shared to important locations of applications. More and more web programs begin to use the anchor (hash) segment (# page) to provide such favorite and shareable links. With the advent of the History API, the anchor can be used to process standard URLs (/pages ). Backbone. Router provides many methods for client routing and can connect to specified actions and events ). For old browsers that do not support the History API, routes provide elegant callback functions and can transparently convert URL fragments.

It seems that the Controller type is missing in Backbone. In fact, every "Route" can be seen as being extended from the Controller. In the traditional sense, the Controller is faulty because it integrates two functions. The first is to control the Model based on the View, and the second is to control users to switch between different views. Backbone separates the user interface and controls the Model by detaching the Router.

Why not create a separate class for the controller? According to the MVC definition, the Controller class should be the implementation of the main logic of your program. In backbone, the specific processing details of the program are separated from the controller layer (for example, processing data within the Model and processing user requests by the Router ), therefore, you do not need a separate Controller class to process the main logic of the program.

The following example shows how to set a route, such as #/certificates/123 or #/certificates/mycertificatename, then, the route creates a View (new CertificateView) based on the certificateID or certificatename ). The following simple code does not process CertificateView Based on ID. However, in actual development, you may need to read/process the Model Based on ID.

var MyRouter = Backbone.Router.extend({    routes: {        "/certificates/:id": "getCertificate",    },    getCertificate: function (id) {        new CertificateView({            el: $("#certificate")        });    }});var router = new MyRouter;Backbone.history.start();

 

References:

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.