How to get started with JavaScript's Backbone. js framework, javascriptbackbone

Source: Internet
Author: User

How to get started with JavaScript's Backbone. js framework, javascriptbackbone

1. Introduction
Recently, I was working on a front-end Optimization for a large online banking project. I needed to use a fat client to optimize it. The general idea was that the front-end obtained data from the backend through Ajax requests and returned data in Jason format, and then displayed on the page. Because of the huge system, the fat client solution will inevitably need to write a large amount of JS Code on the client. I think it is inconvenient for any team to maintain a large amount of unstructured code. So the BackBone came into my sight.
It provides a way for you to structure your JS Code and organize your front-end JS code in an object-oriented way. This is like applying Domain Driven Design in the front end. We can split a very large project by module. Each module can be split into View, Model, and Router according to BackBone requirements.
With backbone, you can use your data as Models. With Models, you can create, verify, destroy, or save data to the server. When an operation on the interface changes the attributes of the model, the model triggers the change event. views used to display the model status will receive the message that the model triggers the change, then, a corresponding response is sent and new data is re-rendered to the interface. In a complete backbone application, you do not need to write the glue code to get the node from the DOM with a special id, or manually update the HTML page, because when the model changes, views will easily update themselves.

2. Features
Backbone is a lightweight front-end framework for structured management of a large number of JS pages. It establishes seamless connections with servers and views and provides a basic framework for building complex applications.
Next, I will briefly describe the main features and features of Backbone:

2.1 lightweight
The source code of Backbone is only about 1000 lines (after comments and blank lines). The file size is only 16 KB, and the dependency library Underscore is only 29KB.
You only need to spend a little time to understand the internal implementation of Backbone, or write a small amount of code to reload some of the Backbone's mechanisms. If you want to perform secondary development based on Backbone, it is not a complicated task.

2.2 structured
Backbone can easily decouple the data, logic, and view on the page and organize the code structure according to Backbone. You can work on data interaction, business logic, and user interface in the project, assigned to multiple colleagues for simultaneous 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 Mechanism
In Backbone, modules can be inherited. You can organize data models, sets, and views in an orderly manner in the application in an object-oriented manner to make the entire architecture clearer; you can also easily reload and extend custom methods.

2.4 establish a seamless connection with the server
Backbone has a set of built-in rules for interacting with server data (you can easily understand the REST architecture if you understand it), and data synchronization is automatically performed in the Model, front-end developers only need to perform operations on the client data, and Backbone will automatically synchronize the operation data to the server.
This is a very interesting thing, because the server data interface is transparent to front-end developers and they do not need to worry about how to interact with the server.
However, the data interfaces provided by the server also need to be compatible with Backbone rules. For a new project, we can try to use these rules to build interfaces. However, if your project already has a set of stable interfaces, you may worry about the risk of interface transformation.
It doesn't matter. We can reload the Backbone. sync method to adapt to the existing data interfaces. For different client environments, we can also implement different data interaction methods. For example, data is synchronized to the server in real time when a user uses the service through a PC browser. When a user uses the service through a mobile terminal, the network environment is considered, we can first synchronize the data to the local database, and then synchronize the data to the server when appropriate. You only need to reload a method to implement these functions.

2.5 interface event management
In MVC, we want to completely separate the interface display from the business logic, but for user-generated interactive events (such as click events ), we often use the bind method similar to jQuery to obtain and bind.
The view in Backbone helps us organize user events and execution methods in an orderly manner. This only requires us to declare a simple expression, for example:

Events: {// when you click an element whose id is "save", execute the 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, etc ), the element can be any selector supported by jQuery (such as tag selector, id selector, and class selector ).
The view automatically binds events in the expression to the selector element. When an element event is triggered, the view automatically calls the method bound to the expression.

2.6 lightweight template Parsing
Template Parsing is a method provided in Underscore. Why should I introduce the Underscore method when introducing the Backbone feature? This method can help us better separate the view structure and logic, and Underscore is the library that Backbone must depend on.
The template parsing method allows us to embed Javascript code in the HTML structure, just like embedding Java code in the JSP page:

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

Through template parsing, we do not need to splice strings when generating the HTML structure dynamically. More importantly, we can manage the HTML structure in the view independently (for example: different States may display different HTML structures. We can define multiple separate template files and load and render them as needed ).

2.7 Custom Event Management

In Backbone, you can use the on or off method to bind and remove custom events. You can use the trigger method to trigger these bound events anywhere. All methods bound to this event will be executed, for example:

Var model = new Backbone. model (); // bind two function models to the custom Event custom in the model object. on ('custom', function (p1, p2) {// todo}); model. on ('custom', function (p1, p2) {// todo}); // triggers the custom Event and calls the two function models bound above. trigger ('custom', 'value1', 'value2'); // remove all methods bound to the custom event. off ('custom'); // triggers the m event, but no function is executed. The function in the event has been removed from the model in the previous step. trigger ('custom ');

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". When an event named "all" is bound to an object, this object triggers any event, both trigger the method bound to the "all" event. Sometimes this method is very useful. For example, we can monitor object state changes through the "all" event.

3. Router
In a single-page application, we use JavaScript to control the switching and display of the interface and obtain data from the server through AJAX.
The possible problem is that when a user wants to return to the previous operation, he may habitually use the browser "return" and "Forward" buttons, the result is that the entire page is switched, because the user does not know that it is in the same page.
For this problem, we often use Hash (Anchor) to record the current position of the user, and use the onhashchange event to listen to the user's "Forward" and "return" actions, however, we found that some earlier browsers (such as IE6) do not support the onhashchange event.
Backbone provides the routing control function. With the vro provided by Backbone, We can bind the routing address with the event function through a simple expression. For example:

Var CustomRouter = Backbone. router. extend ({routes: {'': 'index', // when URL Hash is in the root directory, execute the index method: url # 'LIST': 'getlist ', // when the URL Hash is on the list node, run the getList method: url # list 'detail/: id': 'query', // when the URL Hash is on the detail node, run the query method, and pass the detail data as a parameter to the query method: url # list/1001 '* error': 'showerror' // when the URL Hash does not match the preceding rules, 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 ();

 
Please try to copy this code to your page and access the following addresses in sequence (the URL indicates your page address ):

URLURL#listURL#detail/1001URL#hash1URL#hash2

Please try again using the "return" and "Forward" buttons in the browser to switch back and forth the address you just entered.
As you can see, when the URL Hash changes, the bound method will be executed. When there is no defined Hash, The showError method will be executed, and pass the undefined Hash to this method.
By default, Backbone uses Hash to record address changes. For low-version browsers that do not support onhashchange, it uses setInterval heartbeat to monitor Hash changes. Therefore, you do not have to worry about browser compatibility issues.
For browsers that support the HTML5 pushState feature, Backbone also allows you to create personalized URLs through pushState, but this requires some adaptation on your Web server.
3. Applicability of Backbone

Backbone is not as powerful as jQuery. If you are preparing to build a large or complex single-page Web application, Backbone is no longer suitable.
If you want to apply Backbone to your website page without complicated logic and structure, this will only make your page more complicated and difficult to maintain.
If your project is not complex, but you really like a feature (maybe data model, View Management, or router ), you can extract the source code from Backbone, because in Backbone, the dependencies between modules are not very strong, and you can easily obtain and use a module.

4. Dependent Libraries

You cannot use Backbone independently because its basic functions, DOM operations, and AJAX depend on third-party libraries.

4.1 Underscore
(Required)
Underscore is a basic function library used to improve development efficiency. It encapsulates common operations on collections, arrays, objects, and functions, just as jQuery encapsulates DOM objects, you can easily access and operate JavaScript internal objects through Underscore.
Underscore also provides some very practical function methods, such as function throttling and template parsing.
I will introduce some of the main Underscore methods in the next chapter, but before that, you must understand that Underscore is the library that Backbone must depend on, because many implementations in Backbone are based on Underscore.

4.2 jQuery and Zepto
(Optional)
I believe you will not be unfamiliar with jQuery. It is a cross-browser DOM and AJAX framework.
Zepto can be understood as "jQuery for mobile devices" because it is smaller, faster, and more suitable for running on browsers of mobile devices. It has the same syntax as jQuery, so you can use it like jQuery.
Zepto currently only supports Webkit browsers, so it is compatible with most mobile systems, such as iOS, Adnroid, Saipan, BlackBerry, and Meego. For Windows Phone or Firefox OS, it is not supported yet.
Because jQuery and Zepto have the same syntax, there is no problem for Backbone (of course, you cannot use both) Whether jQuery or Zepto ).
In Backbone, the DOM selector, DOM Event, and AJAX all use the jQuery method. Here they are optional. It is assumed that you do not use the view and AJAX Data Synchronization functions in Backbone, so you do not need to import them.
If you do not want to use jQuery or Zepto, but use other or custom libraries, as long as your library implements the same DOM selector, event management, and AJAX methods as jQuery syntax, then there will be no problems.
Backbone allows you to dynamically configure the required third-party library through the setDomLibrary method, which is often used in:
Although your custom library contains methods with the same syntax as jQuery, the global variables are not $, and you want to keep the existing names. In this case, you can use the setDomLibrary method to set the object to be referenced inside the Backbone.
You want to check your environment to determine which database is more suitable for use. For example, if you use a PC browser to access the file, the file is loaded into jQuery. If you use a mobile terminal to access the file, the file is loaded into Zepto.

 

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.