JavaScript client MVC Framework details different framework usage

Source: Internet
Author: User

15 years ago, many people used tools such as Perl and ColdFusion to build websites. We often write scripts that can query databases at the top of the page, necessary conversions for data applications, and displaying data at the bottom of the same script. This type of architecture is suitable for adding a simple "Contact us" form to a website. However, as applications become more complex, this method cannot be scaled to handle more complex problems. Most Web applications have now standardized the Model-View-controller (MVC) architecture and used separate code to implement business logic, display logic, and user interaction (Routing) logic. The emergence of various frameworks from Spring MVC to Rails can help you quickly implement MVC-based Web applications.

Several years ago, jQuery was the mainstream library used to build JavaScript applications on the client. However, with the increasing complexity of JavaScript in applications, jQuery becomes a necessary and inadequate technology for dealing with complexity. For example, a single page application for the to-do list can contain an emergency to-do list, a complete to-do list, and a one-day to-do list, and an expiration to-do list. What happens when I delete a to-do list? If the task is urgent but has expired, you may need to manually write code to delete the task from three or four different positions in the view. If you need to delete an object or change its related objects displayed on the screen after deleting it, the complexity becomes uncontrollable.

The client MVC framework is designed to solve such problems, and most frameworks are outstanding. But how do you select the appropriate framework from many JavaScript client MVC frameworks. This article briefly introduces some of the most popular frameworks. And how to select an appropriate framework for a given use case.

Backbone. js

In terms of usage, Backbone is the most popular Client MVC framework so far. It has been widely used in various development communities. Rails developers have consistently adopted a high level of resources, and many popular resources have emerged, such as thoughtbot (a highly respected Rails consulting company) launched Backbone on Rails (see references ). The advantage of Backbone. js is that it is well integrated with the visualization-based status transmission Web service. If you use the RESTful JavaScript Object Notation (JSON) model for backend data and follow the conventions expected by Backbone (matching the conventions in Rails ), you can connect Backbone to the server without writing any code, saving a lot of time.

In Backbone, an application contains a set (user or article), a model (single user or article), a view, and a router. The view in Backbone. js is non-prescriptive and allows you to use your favorite JavaScript template or framework. A Router combines a Rail-style router with a traditional MVC controller to obtain the given URL and notify the framework of the Code to run. The Backbone. js router code in Listing 1 provides an example.

List 1. Sample Backbone. js router code

Var Workspace = Backbone. Router. extend ({

Routes :{

"Help": "help", // # help "search/: query": "search", // # search/kiwis "search/: query/p: page ": "search" // # search/kiwis/p7 },

Help: function (){

....

},

Search: function (query, page ){

.....

}

});

Backbone. js comes with an Underscore. js copy. Underscore. js is a set of utilities that simplify JavaScript writing in a more functional way and support a series of useful set-based operations. It also includes Backbone. history, which helps you skillfully navigate pages.

The main advantage of Backbone. js is its automatic integration with servers. If this is suitable for your use cases, it is worthwhile to learn how to use Backbone. js. You can use some frameworks to obtain basic Backbone. js knowledge that may take one or two days to learn within an hour. This is ideal for large projects that last for at least a few weeks.

Backbone. js is still not a good solution. You may need to write a considerable amount of code to handle potential memory leaks and other issues. You may need to experiment with several methods to view the rendered content before you can find a method that truly meets your needs.

Spine. js

Spine. js is usually compared with Backbone. js. It is affected by Backbone. js and is similar to the former in terms of usage. Spine. js Contains classes, models, controllers, and views, which are more traditional than the collection introduced by Backbone. js.

Spine. js is written using CoffeeScript (see references), which makes it more concise and (in my opinion) easier to read source code. To learn how Spine. js works, you need to be familiar with CoffeeScript. However, you do not have to use CoffeeScript to build the Spine. js application. However, if CoffeeScript has been used for building, you can access CoffeeScript features (such as classes ). CoffeeScript uses prototype inheritance instead of classic inheritance, so it cannot support classes in local JavaScript. CoffeeScript uses some very standard modes to provide classes for developers who want to use them. If you use pure JavaScript to write the Spine. js application, you only need to use it, which allows you to compile the class without writing CoffeeScript code.

Models, controllers, and views in Spine. js are implemented using classes, so you can write classes and instance methods at the same time. The model is responsible for processing business logic and belongs to the module class. You can expand and include other modules to reuse attributes and functions in a hybrid manner. The model can be automatically serialized to JSON and persisted by using local storage only. Alternatively, you can use Asynchronous JavaScript + XML (Ajax) to persist the object to the server. Like Backbone. js, Spine. js now provides reasonable default settings that can be persisted through Ajax, but you can still write your own specific implementations as necessary, which is very simple. Listing 2 shows an example of CoffeeScript code from a Spine. js application.

Listing 2. CoffeeScript in the Spine. js Application

Class Contact extends Spine. Model

@ Configure "Contact", "first_name", "last_name"

@ Filter: (query)->

@ Select (c)->

C. first_name.indexOf (query) is not-1

FullName:-> [@ first_name, @ last_name]. join ('')

The main difference between Spine. js and Backbone. js is the way they process server interactions. Backbone. js will wait for the server to respond before displaying the response. If you try to delete, insert, or update an element, the user interface (UI) will not be refreshed until the operation is completed successfully. Spine. js focuses on real-time UI updates and handles Ajax servers during background processing. This kind of update is a very important practice, and it is also the main factor to consider when selecting between the popular frameworks with good editing skills.

If your goal is to create a client experience that is secondary to server status updates, Spine. js may be a better choice. If the server is still used to check the validity of status changes, Backbone. js may be more suitable. Spine. js provides a more responsive UI. However, if an element is successfully deleted, but the server sends a response, you are not allowed to delete it because it is being used by others, what will happen? There are some emergency solutions to this problem, but generally Spine. js is more suitable for users to operate their own (rather than sharing) data. A common use case of Spine. js is the shopping cart, where all verification can be processed on the client.

Knockout

People may argue whether the tools discussed so far are true MVC frameworks in the original sense. Knockout explicitly implements Model-View-model (MVVM), rather than classic MVC. However, do not impede your decision-making. When selecting a framework, it is more important to view the features provided than the acronyms or categories of the first letter.

Knockout. js is particularly popular among Microsoft. NET developers who are familiar with MVVM models. Knockout. js is a good choice for binding model states to view cases through declaration. Knockout. js is an ideal choice for the previous example to-do list application. The main to-do list subset of the application has its own view, after deleting a to-do list, you need to update all lists.

In Knockout. js, you will create models, view models, and views. Like in Spine. js and Backbone. js, Ajax is responsible for processing business logic, verification, and interaction with remote servers (assuming you are not just creating a local application ). The view model code is responsible for retaining and operating model data. For example, a view model may contain methods for adding, editing, and deleting content items from the list. The view model is very close to the Controller in the traditional MVC Architecture. A view is a template that displays information on the screen. In Knockout. js, these can be declared and bound to the view model (easy to get started ). Some students can master and use Knockout within one hour, and can build extraordinary (non-trivial) applications within three hours.

Generally, Knockout. js is suitable for small and simple projects. People often use Backbone. js or Spine. js for larger and more complex projects. That is to say, experienced Knockout. js developers can create very complex and easy-to-maintain applications. If you want to use Knockout. js, you should also consider Angular. js and Sammy. js (see references). The latter two are relatively lightweight and easy-to-start frameworks.

Batman. js

Batman. js is an interesting new framework launched by JSConf in 2011, but it takes several months to download it. Batman. js has been gaining attention from programmers who like and develop MVC applications. On the surface, Batman is similar to Knockout. js in terms of ease of entry and support for view declaration binding. Batman. js provides some other functions, including the optional full-stack framework for Automatic Code generators, build tools, and even backend nodes. js server code, which can implement your server-side API.

Like Knockout. js, Batman. js also uses view binding. Listing 3 shows some sample view code.

Listing 3. view code example in Batman. js

<Ul id = "items">

<Li data-foreach-todo = "Todo. all" data-mixin = "animation">

<Input type = "checkbox" data-bind = "todo. isDone" data-event-change = "todo. save"/>

<Label data-bind = "todo. body" data-addclass-done = "todo. isDone"

Data-mixin = "editable"> </label>

<A data-event-click = "todo. destroy"> delete </a>

</Li>

<Li> <span data-bind = "Todo. all. length"> </span>

<Span data-bind = "'item' | pluralize Todo. all. length"> </span> </li>

</Ul>

Listing 3The code in is valid HTML5 and contains some additional attributes for Batman to bind data and events. In Batman. js, your applications include models, views, and controllers. The model supports the verification function to implement lifecycle events, including a built-in identity map, and can be notified (actively recorded style) how to stick to the use,Batman.RestStorage,Batman.RailsStorageOr custom implementation. The view is a JavaScript class that presents templates written in pure HTML.data-*Attribute: the component that binds the model data and triggers the event processor. The controller is a permanent object that processes events from the view, accesses the model data, and presents the corresponding view.

Select a JavaScript framework

If you are working on a long-term big project, it is necessary to understand Backbone. js or Spine. js because they are widely used and can solve your problems. However, even with these projects, you need to understand that you do not need to use a mature server-side MVC framework, but you still need to write infrastructure code.

It is necessary to try to use a framework with declarative binding in the view. Such frameworks have different advantages and disadvantages from projects such as Backbone. js. If you want to use declarative view binding, take some time to study the additional functions provided by the updated Batman. js framework. Although Batman. js is not as popular as other frameworks, it is developing rapidly and provides richer features than the common client MVC framework.

It is necessary to prototype these frameworks in different frameworks and feel their usage. Especially for the client MVC Framework, prototyping is one of the fastest and most effective methods to select from different options. One way is to let each team member spend one or two days, use different frameworks for prototyping, and then review and discuss the results. The worst case is that if you have another framework to choose from, you can spend an additional day or so to build the two concepts until you select the framework that best fits your use case.

Consider flexibility. It is a daunting task for many frameworks to carefully consider what you can do to reduce the dependence on the framework. Develop a backup solution for migrating data to another framework in the next 12 to 18 months, in case you find that the requirements and the selected framework are not as expected.

Conclusion

The JavaScript client MVC framework is still immature. This field is rapidly changing, and there is a lack of best practices for consensus. For large projects, Backbone. js and Spine. js are very popular and well supported. If you prefer to declare view binding, Knockout. js and Batman. js are both good choices.

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.