How to organize code in large JavaScript applications?

Source: Internet
Author: User
Abstract:We often see that JavaScript, CSS, and image files are differentiated by file type in Web applications. This habit is still competent in the past web development scenarios. However, with the development of Web apps, JavaScript applications become more and more complex, and developers need a clearer and more efficient file structure.

Cliff Meyers is a front-end engineer familiar with HTML5, JavaScript, and J2EE development. During the development process, he summarized his file structure in response to the increasingly large JavaScript Application, it is well recognized by other developers. Csdn compilation is as follows:

Clothes stacked on the floor

First, let's take a look at angular-seed, which is an official entry-level project for angularjs application development. Its file structure is as follows:

  • CSS/
  • IMG/
  • JS/
    • App. js
    • Controllers. js
    • Directives. js
    • Filters. js
    • Services. js
  • LIB/
  • Partials/

It looks like a pile of clothes stacked on the floor by type, a pile of so, a pile of underwear, a pile of shirts, and so on. You know that there are black wool so In the heap of the corner, but you still need to spend some time searching.

This type of organization is messy. Once your code contains 6, 7, or more controllers or services, file management becomes hard to handle: it is difficult to find the desired object, it is also difficult to understand the change set of files in source code control.

Sock drawer

Another common form of Javascript file structure is to classify files by prototype. We continue to use clothes arrangement as a metaphor: now we have bought a wardrobe with many drawers, and we plan to put the so in one of the drawers, and put the underwear in another drawer, fold the shirt neatly in the Third drawer ......

Imagine that we are developing a simple e-commerce website, including the login process, product catalog, and shopping cart UI. Likewise, files are divided into the following prototypes: Models (business logic and status), controllers, and services (HTTP/JSON Endpoint Encryption ), by default, angular is regarded as a non-General "service" architecture. Therefore, our JavaScript directory becomes like this:

  • Controllers/

    • Logincontroller. js
    • Registrationcontroller. js
    • Productdetailcontroller. js
    • Searchresultscontroller. js
  • Directives. js
  • Filters. js
  • Models/
    • Cartmodel. js
    • Productmodel. js
    • Searchresultsmodel. js
    • Usermodel. js
  • Services/
    • Cartservice. js
    • Userservice. js
    • Productservice. js

Yes, now you can use the tree file directory or IDE shortcut to more easily find the file. The Changeset in source code control can also clearly describe the file modification record. Although significant improvements have been made, there are still some limitations.

Imagine that you are in the office now and suddenly find that there is a business trip tomorrow and you need some dry-cleaned clothes. Therefore, call the house and tell the other half to hand over the black and blue suits to the cleaners, there are also black ties with gray shirts, white shirts with Pure Yellow Ties. If your other half is not familiar with the wardrobe, how can you pick out your right needs from Three Yellow Ties?

Modular

I hope that the clothes metaphor does not make you feel too old. Here is an example:

  • Your partner is a new developer who is asked to fix a bug in this complex application.
  • After scanning these folders, the folders such as controllers, models, and services are arranged neatly, but the dependency between objects is still unclear.
  • For some reason, he wants to reuse part of the code, which needs to collect related files from various folders and often misses objects in some folders.

Believe it or not, you seldom re-use a lot of code in the new project, but you may need to re-use the entire module such as the login system. So, is it better to divide files by function? The following file structure is the application structure after function division:

  • Cart/

    • Cartmodel. js
    • Cartservice. js
  • Common/
    • Directives. js
    • Filters. js
  • Product/
    • Search/

      • Searchresultscontroller. js
      • Searchresultsmodel. js
    • Productdetailcontroller. js
    • Productmodel. js
    • Productservice. js
  • User/
    • Logincontroller. js
    • Registrationcontroller. js
    • Usermodel. js
    • Userservice. js

Although there are space limitations in the real world and it is difficult to organize clothes at will, similar processing in programming is zero cost.

Now, even new developers can understand the application functions by naming top-level folders. Files in the same folder may be dependent on each other, in addition, you can easily understand the principles of login, registration, and other functions simply by browsing the file organization structure. You can copy and paste the code in the new project to reuse the code.

With angularjs, we can further organize the relevant code into modules:

12345678910111213 var userModule = angular.module('userModule',[]);  userModule.factory('userService',
[
'$http'function($http)
{
  return new UserService($http);}]);  userModule.factory('userModel',
[
'userService'function(userService)
{
  return new UserModel(userService);}]);  userModule.controller('loginController',
[
'$scope''userModel',
LoginController]);
  userModule.controller('registrationController',
[
'$scope''userModel',
RegistrationController]);

If we put the usermodule. js file in the user folder, it becomes the "Manifest" of the object used in this module. This is also suitable for placing some loading commands in requirejs or browserify.

How to deal with common code

Each application has some code that is widely used in multiple modules. We often use folders named "commom" or "shared" to store these functional codes. How can we deal with these general codes?

  1. If the objects in the module need to directly access several "common" objects, provide several facade (appearance mode) for these objects ). This helps reduce the dependent size of each object, and too many associated objects usually mean a bad code structure.
  2. If the "General" module becomes too large, you need to divide it into multiple sub-modules by functional areas. Make sure that each application module only uses the "common" module required by it, which is a variant of the "interface isolation principle" in solid.
  3. Add an object to the root scope ($ rootscope), so that the scope can be used. This is suitable for situations where multiple controllers depend on the same object (such as "permissionsmodel.
  4. Use events when decoupling two components that are not explicitly referenced by each other. The $ emit, $ broadcast, and $ on methods of scope objects in angular make this method realistic. The controller can trigger an event to execute some actions, and then receives the corresponding notification after the action ends.

    Original article: Cliff Meyers
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.