JavaScript Backbone.js Framework Introductory Learning Guide _ Basics

Source: Internet
Author: User

1. Introduction
recently in doing a large online banking project optimization, need to use a FAT client optimization, the idea is that the front-end through Ajax request to the back-end to get the data, in Jason's format returned, and then displayed on the page. Because this system is very huge, the FAT client solution inevitably needs to write a large number of JS code on the client. I think for any team, a lot of unstructured code is very inconvenient to maintain. So backbone into my line of sight.
It provides a way for you to structure your JS code so that you can organize your front-end JS code in an object-oriented way. It's like we're using domain driven design on the front end. We can split a very large item by module. Inside each module can be backbone according to the requirements of cut into view, Model, Router.
By backbone, you can use your data as a models, models you can create data, validate data, destroy it, or save it to a server. When the interface of the operation caused by the changes in model, the model will trigger the change of events, those used to show the model state of the views will accept the model to trigger changing the message, and then send the corresponding response, and to render new data to the interface. In a complete backbone application, you don't have to write the glue code to get the node from the DOM with a special ID, or to manually update the HTML page, because when the model changes, the views will simply update themselves.

2. Features
Backbone is a lightweight front-end framework for a large number of JS in structured management pages, establishing seamless connectivity to servers and views, and providing the infrastructure for building complex applications.
Let me first briefly explain the main features and characteristics of the backbone:

2.1 Lightweight
Backbone's source code is only about 1000 lines (to comment and empty lines), the file size is only 16KB, plus dependent library underscore, also only 29KB.
You only need to spend a little time, you can easily understand backbone internal implementation, or write a small number of code to overload backbone part of the mechanism, if you want to build on the basis of backbone two times, it is not a complicated matter.

2.2 Structured
backbone can easily be a page of data, logic, visual graphic decoupling, according to backbone code structure organization, you can project data interaction, business logic, user interface and other work, assigned to several colleagues at the same time development, and can be organized together in an orderly manner. At the same time, this is very helpful for the maintenance and development of large and complex projects.

2.3 Inheritance Mechanisms
in backbone, modules can be inherited, and you can organize the data models, collections, and views in an application in an object-oriented way, making the entire architecture clearer, and easily overloading and extending the custom methods.

2.4 Establish seamless connection with the server
a set of interactive rules for server data is built into the backbone (if you understand the rest architecture, you can easily understand them), and the data synchronization work will be done automatically in model, the front-end developers only need to operate the client data, Backbone automatically synchronizes the operation's data to the server.
This is a very interesting thing because the server data interface is transparent to the front-end developers and they don't need to care about how to interact with the server.
However, the data interface provided by the server also requires compatible backbone rules, and for a new project, we can try to build the interface with this set of rules. But if you have a stable interface in your project, you may be worried about the risk of interface modification.
It doesn't matter, we can use the overloaded Backbone.sync method to fit the existing data interface, for different client environments, we can also implement different data interaction. For example, when a user uses the service through a PC browser, the data is synchronized to the server in real time, and when the user uses the service through the mobile terminal, we can synchronize the data to the local database and synchronize to the server at the right time. And these only need you to overload a method can be achieved.

2.5 Interface Event Management
in MVC, we want to be able to completely separate the interface presentation from the business logic, but for user-generated interaction events (such as click events), we often get and bind through a bind method like jquery.
The view in backbone helps us organize the user events and execution methods in an orderly manner, which only requires us to declare a simple expression, such as:

Events: { 
  //click the element with ID "save" to execute the view's Add Method 
  ' click #save ': ' Add ', ' 
  mousedown button ': ' Show ', 
  ' MouseOver. Button ': ' Hide ' 
} 

In an expression, the event name can be any DOM event (such as Click, MouseOver, KeyPress, and so on), and the element can be any selector supported by jquery (such as tag Selector, ID selector, class selector, and so on).
The view automatically binds the events in the expression to the selector element, and when the event of the element is triggered, the view automatically invokes the method that is bound in the expression.

2.6 Lightweight Template parsing
template parsing is a method that is provided in underscore. Why should I introduce a method in underscore when introducing the backbone feature? Because this method can help us to better separate view structure and logic, and underscore is the library that backbone must depend on.
Template parsing allows us to mix and embed JS code in the HTML structure, just like embedding Java code in a JSP page:

<ul> 
  <% for (var i = 0; i < len; i++) {%> 
  <li><%=data[i].title%></li> 
  <%}%> 
</li> 

Through template parsing, we don't need to concatenate strings when dynamically generating HTML structures, and more importantly, we can manage HTML structures in the view independently (for example: different states may display different HTML structures, we can define multiple separate template files, load and render on demand).

2.7 Custom Event Management

In backbone, you can use the on or off method to bind and remove custom events. Anywhere, you can use the trigger method to trigger these bound events, and any method that binds the event will be executed, such as:

var model = new Backbone.model (); 
Bind two functions to custom events custom in the Model object 
model.on (' Custom ', function (P1, p2) { 
  /Todo 
}); 
Model.on (' Custom ', function (P1, p2) { 
  //Todo 
}); 
Triggers the custom event, which will invoke the two functions that are bound above 
model.trigger (' Custom ', ' value1 ', ' value2 '); 
Remove all the methods bound in the custom event 
Model.off (' Custom '); 
The custom event is triggered, but no function is executed, and the function already in the event has been removed from the 
model.trigger (' Custom ') in the previous step; 
 

If you are familiar with jquery, you will find that they are very similar to the bind, unbind, and trigger methods in jquery.
In addition, backbone supports a special event "all", which, when an event is bound to an object named "All", triggers the method that is bound in the "all" event when any event is triggered. Sometimes this approach can be very useful, for example, we can listen to the change of object state through the "all" event.

3. Router
in a single-page application, we control interface switching and presentation through JavaScript and get data from the server via Ajax. The problem with
may be that when the user wants to return to the previous action, he may habitually use the browser "return" and "Forward" buttons, and the result is that the entire page is switched because the user does not know that he is on the same page.
For this problem, we often record the user's current position through the hash (anchor point), and listen to the user's "forward" and "return" actions through the Onhashchange event. However, we found that some low-level browsers, such as IE6, do not support the Onhashchange event. The
backbone provides routing control, and through the routers provided by backbone, we can bind routing addresses and event functions together through a simple expression, such as:

var customrouter = Backbone.Router.extend ({ 
  routes: {' 
    : ' index ',////When URL hash executes the index method at root: url# 
    ' list ': ' GetList ',///When URL hash is executed at the list node GetList method: Url#list 
    ' detail/:id ': ' Query ',///When URL hash executes the query method at the detail node, The detail data is passed as a parameter to the Query method: url#list/1001 
    ' *error ': ' showerror '///when the URL hash does not match the above rule, execute the error method 
  }, 
  index : function () { 
    alert (' index '); 
  }, 
  getlist:function () { 
    alert (' getlist '); 
  }, 
  query: function (ID) { 
    alert (' Query ID: ' + id); 
  }, 
  showerror:function (Error) { 
    alert (' ERROR hash: ' + error ); 
  }, 
}); 
 
var custom = new Customrouter (); 
Backbone.history.start (); 


Try copying this code into your page, and then accessing the following address (where the URL represents your page address):

URL
url#list
url#detail/1001
url#hash1
url#hash2

Try again and again with the browser's "back" and "forward" buttons to switch back to the address you just entered.
As you can see, when the URL hash changes, the method is executed, and when the hash is not defined, the ShowError method is executed and the undefined hash is passed to the method.
Backbone defaults to record address changes by hashing, and for browsers that do not support Onhashchange, the setinterval heartbeat listens for hash changes, so you don't have to worry about browser compatibility issues.
For browsers that support HTML5 Pushstate features, backbone also allows you to create personalized URLs via Pushstate, but this requires your Web server to do some matching.
3. Applicability of Backbone

Backbone is not as powerful as jquery, and if you are preparing to build a large or complex single-page Web application, then backbone is a good fit.
If you want to apply backbone to your site pages, and there is no complex logic and structure on the page, this will only make your pages more cumbersome and difficult to maintain.
If your project is not complex, but you are deeply interested in some of its features (possibly data models, view management, or routers), then you can extract this part of the source from the backbone, because in backbone, the dependencies between the modules are not very strong, You can easily get and use one of these modules.

4. Dependent libraries

You can't use backbone on your own because its underlying functions, DOM operations, Ajax all depend on Third-party libraries.

4.1 Underscore
(required)
underscore is a base function library for improving development efficiency, encapsulating common operations on collections, arrays, objects, functions, Just like jquery encapsulates Dom objects, you can easily access and manipulate JavaScript internal objects through underscore. The
underscore also provides some very useful functional methods, such as function throttling, template parsing, and so on.
Some of the main methods in underscore, which I'll explain in more detail in the next chapter, but before you have to understand: underscore is a library that backbone must rely on because many implementations in backbone are based on underscore.

4.2 jquery and Zepto
(optional)
I'm sure you'll never be unfamiliar with jquery, it's a cross-browser DOM and Ajax framework.
For Zepto you can understand "mobile jquery" because it is smaller, faster, and better suited to run on mobile device browsers, which is the same as jquery syntax, so you can use it like jquery.
Zepto currently supports only browsers for the WebKit kernel, so it can be compatible with most mobile systems, such as iOS, Adnroid, Symbian, BlackBerry, and Meego, but it is not supported for Windows Phone or Firefox OS.
Because jquery is the same as Zepto syntax, for backbone, you have no problem using jquery or zepto (of course, you can't use both at the same time).
In backbone, the DOM selector, DOM event, and Ajax all use the jquery approach. The reason why they are optional is that you don't need to import them if you don't use the view and AJAX data synchronization features in backbone.
If you don't want to use jquery or zepto, but use other, or custom libraries, if you implement the same DOM selector, event management, and Ajax methods as the jquery syntax in your library, then there's no problem.
Backbone allows you to dynamically configure the Third-party libraries that need to be used through the Setdomlibrary method, which is often used to:
Your custom library contains methods that are the same syntax as jquery, but the global variable is not $ and you want to keep the existing name. At this point you can set it to an object that is referenced within backbone by the Setdomlibrary method.
You want to check the user's environment to determine which library is more appropriate to use. For example, if a user accesses using a PC browser, load jquery and load Zepto if the user accesses through the mobile terminal.

Related Article

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.