Modular programming of JavaScript

Source: Internet
Author: User
Tags jquery library

As Web sites become "Internet Applications", JavaScript code embedded in Web pages is becoming larger and more complex.

Web pages are becoming more and more like desktop programs, requiring a collaborative team, schedule management, unit testing, etc... Developers have to use the software engineering approach to manage the business logic of the Web page.

JavaScript modular programming has become an urgent requirement. Ideally, developers only need to implement core business logic, and others can load modules that others have already written.

However, JavaScript is not a modular programming language, it does not support the class, not to mention the module. (The ECMAScript standard Sixth Edition, which is under development, will officially support "Class" and "module", but it still takes a long time to put into practice.) )

The JavaScript community has made a lot of efforts to achieve the "module" effect in the existing operating environment. This article summarizes the current "JavaScript modular Programming" best practices and shows how to put it into practice. Although this is not a beginner tutorial, you can understand the basic syntax of JavaScript a little bit.

First, the original wording

A module is a set of methods for implementing a specific function.

Simply put the different functions (and the variables that record the state) together, even if it is a module.

function M1 () {
//...
}

function m2 () {
//...
}

The above functions M1 () and M2 () to form a module. When used, call directly on the line.

The disadvantage of this approach is obvious: "Pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship.

Ii. the wording of the object

In order to solve the above shortcomings, the module can be written as an object, all the module members are placed in this object.

var module1 = new Object ({

_count:0,

M1:function () {
//...
},

M2:function () {
//...
}

});

The above functions M1 () and M2 () are encapsulated in the Module1 object. When used, it is called the property of the object.

MODULE1.M1 ();

However, such a notation exposes all module members, and the internal state can be overridden externally. For example, external code can directly change the value of an internal counter.

Module1._count = 5;

Iii. immediate execution of function notation

Using the Execute functions now (immediately-invoked function Expression,iife), you can achieve the purpose of not exposing private members.

var Module1 = (function () {

var _count = 0;

var m1 = function () {
//...
};

var m2 = function () {
//...
};

return {
M1:M1,
M2:m2
};

})();

Using the notation above, the external code cannot read the internal _count variable.

Console.info (Module1._count); Undefined

Module1 is the basic way of writing JavaScript modules. The following, and then processing the writing.

Four, amplification mode

If a module is large and must be divided into several parts, or if one module needs to inherit another module, then it is necessary to use "magnification mode" (augmentation).

var Module1 = (function (mod) {

MOD.M3 = function () {
//...
};

return mod;

}) (Module1);

The code above adds a new method M3 () to the Module1 module and then returns the new Module1 module.

Five, wide magnification mode (Loose augmentation)

In a browser environment, parts of the module are usually obtained from the web, and sometimes it is not possible to know which part is loaded first. If you use the previous section, the first part of the execution is likely to load a nonexistent empty object, then use the "wide magnification mode".

var Module1 = (function (mod) {

//...

return mod;

}) (Window.module1 | | {});

In contrast to Loupe mode, the wide magnification mode is a parameter that executes function immediately, which can be an empty object.

VI. Input Global Variables

Independence is an important feature of the module and it is best not to interact directly with other parts of the program.

In order to call global variables inside a module, you must explicitly enter other variables into the module.

var Module1 = (function ($, YAHOO) {

//...

}) (JQuery, YAHOO);

The above Module1 module needs to use the jquery library and Yui Library, the two libraries (actually two modules) as a parameter input module1. In addition to ensuring the independence of the module, it also makes the dependency between modules obvious. For more discussion on this, see Ben Cherry's famous article, "JavaScript Module pattern:in-depth."

The first part of this series introduces the basic wording of the JavaScript module, and today describes how to use the module in a canonical manner.

(next to the above)

VII. Specification of modules

First think about why the module is important?

Because of the module, we can more easily use other people's code, want what function, load what module.

However, this has a premise, that is, we must write the module in the same way, otherwise you have your writing, I have my writing, it is not messy set! This is even more important considering that the JavaScript module does not yet have an official specification.

Currently, there are two types of JavaScript module specifications available: Commonjs and AMD. I mainly introduce AMD, but start with Commonjs.

Eight, CommonJS

In 2009, American programmer Ryan Dahl created the node. JS project to use the JavaScript language for server-side programming.

This symbol "JavaScript modular programming" was formally born. Because frankly speaking, in the browser environment, no module is not particularly big problem, after all, the complexity of the Web-page program is limited, but on the server side, must have modules, and the operating system and other applications to interact with, otherwise it is impossible to program.

Node. JS's module system is implemented with reference to the COMMONJS specification. In Commonjs, there is a global method require () that is used to load the module. Assuming that a mathematical module is math.js, it can be loaded as follows.

var math = require (' math ');

Then, you can invoke the method provided by the module:

var math = require (' math ');

Math.add (2,3); 5

Since this series is primarily for browser programming and does not involve node. js, there is no more introduction to COMMONJS. As long as we know here, require () is used to load the module on the line.

Nine, the browser environment

With the server-side module, it is natural for everyone to want the client module. And it is best to be compatible, a module without modification, both server and browser can be run.

However, due to a significant limitation, the COMMONJS specification does not apply to the browser environment. or the previous section of the code, if run in the browser, there will be a big problem, you can see it?

var math = require (' math ');

Math.add (2, 3);

The second line, Math.add (2, 3), runs after the first line of require (' math '), so it must wait until the math.js load is complete. That is, if the load time is long, the entire application will stop there and so on.

This is not a problem on the server side, because all the modules are stored on the local hard disk, can be loaded synchronously, waiting time is the hard disk read time. However, for the browser, this is a big problem, because the modules are placed on the server side, the waiting time depends on the speed of the network, it may take a long time, the browser is in "Suspended animation" status.

As a result, the browser-side module cannot be "synchronous-loaded" (synchronous) and can only take "asynchronous load" (asynchronous). This is the background to the birth of the AMD specification.

X. AMD

AMD is the abbreviation for "Asynchronous module definition", meaning "async module definition". It loads the module asynchronously, and the module's load does not affect the execution of the statement behind it. All statements that rely on this module are defined in a callback function that will not run until the load is complete.

AMD also uses the Require () statement to load the module, but unlike COMMONJS, it requires two parameters:

Require ([module], callback);

The first parameter, [module], is an array in which the member is the module to be loaded, and the second parameter, callback, is the callback function after the load succeeds. If you rewrite the previous code in AMD form, this is the following:

Require ([' math '], function (math) {

Math.add (2, 3);

});

Math.add () is not synchronized with the math module, and the browser does not take place in animation. So it's clear that AMD is better suited for a browser environment.

Currently, there are two main JavaScript libraries that implement the AMD specification: Require.js and Curl.js. The third part of this series will introduce require.js to further explain AMD's usage and how to put modular programming into combat.

I am using a very popular library require.js.

First, why use Require.js?

At the earliest, all JavaScript code was written in a single file, as long as the file was loaded. Later, the code more and more, a file is not enough, must be divided into multiple files, loaded sequentially. The following page code, I believe many people have seen.

<script src= "1.js" ></script>
<script src= "2.js" ></script>
<script src= "3.js" ></script>
<script src= "4.js" ></script>
<script src= "5.js" ></script>
<script src= "6.js" ></script>

This code loads multiple JS files in turn.

This kind of writing has a lot of shortcomings. First of all, when loading, the browser stops the page rendering, the more files loaded, the longer the Web page loses response time, and secondly, because of the existence of a dependency between JS files, Therefore, the load order must be strictly guaranteed (for example, 1.js above 2.js), the most dependent module must be put to the last load, when the dependency is very complex, code writing and maintenance will become difficult.

The birth of require.js is to solve these two problems:

  

(1) To realize the asynchronous loading of JS file, to avoid web page loss response;

(2) The dependency between the management module, easy to write and maintain the code.

Second, the loading of require.js

The first step in using Require.js is to go to the official website to download the latest version first.

After downloading, assume that it is placed under the JS subdirectory, it can be loaded.

<script src= "Js/require.js" ></script>

One might think that loading this file could also cause the webpage to lose its response. There are two solutions, one is to put it on the bottom of the page to load, the other is written as follows:

<script src= "Js/require.js" defer async= "true" ></script>

The async attribute indicates that the file needs to be loaded asynchronously to prevent the webpage from losing its response. IE does not support this property, only support defer, so put defer also write on.

After loading require.js, the next step will be to load our own code. Suppose our own code file is Main.js, also placed under the JS directory. Well, just write the following:

<script src= "Js/require.js" data-main= "Js/main"></script>

The purpose of the Data-main property is to specify the main module of the Web program. In the example above, is the JS directory below the main.js, this file will be the first to be loaded require.js. Since the require.js default file suffix is JS, main.js can be shortened to main.

Three, the main module of the wording

In the previous section of the main.js, I called it the "main module", meaning the entry code for the entire page. It's kind of like the C-language main () function, where all the code starts running.

See below, how to write Main.js.

If our code does not depend on any other modules, then you can write the JavaScript code directly.

Main.js

Alert ("Loaded successfully! ");

But in this case, there is no need to use the require.js. The real common scenario is that the main module relies on other modules, and the Require () function defined by the AMD specification is used.

Main.js

Require ([' Modulea ', ' Moduleb ', ' Modulec '], function (Modulea, Moduleb, Modulec) {

Some code here

});

The Require () function accepts two parameters. The first parameter is an array that represents the dependent module, the example above is [' Modulea ', ' Moduleb ', ' modulec ', i.e. the main module relies on these three modules; The second parameter is a callback function, which is called when the module specified by the current polygon is loaded successfully. The loaded module passes in the function as a parameter, allowing the modules to be used inside the callback function.

Require () asynchronously loads Modulea,moduleb and Modulec, the browser does not lose its response; it specifies a callback function that only the preceding modules will run after they are successfully loaded, resolving the dependency problem.

Below, let's look at a practical example.

Assuming that the main module relies on the three modules of jquery, underscore, and backbone, Main.js can write this:

Require ([' jquery ', ' underscore ', ' backbone '), function ($, _, backbone) {

Some code here

});

Require.js will load jquery, underscore, and backbone before running the callback function. The code for the main module is written in the callback function.

Iv. Loading of modules

In the last example of the previous section, the dependency module of the main module is [' jquery ', ' underscore ', ' backbone ']. By default, Require.js assumes that the three modules are in the same directory as Main.js, with filenames jquery.js,underscore.js and backbone.js, and then loaded automatically.

Using the Require.config () method, we can customize the load behavior of the module. Require.config () is written on the head of the main module (main.js). A parameter is an object that specifies the load path for each module by the paths property of the object.

Require.config ({

Paths: {

"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"

}

});

The above code gives the file name of three modules, and the path defaults to main.js in the same directory (JS subdirectory). If these modules are in a different directory, such as the Js/lib directory, there are two ways to do it. One is to specify the path individually.

Require.config ({

Paths: {

"jquery": "lib/jquery.min",
"Underscore": "lib/underscore.min",
"Backbone": "lib/backbone.min"

}

});

The other is to directly change the base directory (BASEURL).

Require.config ({

    BASEURL: "Js/lib",

Paths: {

"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"

}

});

If a module is on a different host, you can also specify its URL directly, for example:

Require.config ({

Paths: {

"jquery": "Https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"

}

});

Require.js requirements, each module is a separate JS file. In this case, if multiple modules are loaded, the HTTP request will be issued multiple times, which will affect the load speed of the Web page. As a result, Require.js provides an optimization tool that, when the module is deployed, can be used to merge multiple modules into a single file, reducing the number of HTTP requests.

V. How AMD modules are written

Require.js loaded modules, using AMD specifications. In other words, the module must be written in accordance with AMD's requirements.

Specifically, the module must be defined using a specific define () function. If a module does not depend on other modules, it can be directly defined in the Define () function.

Suppose you now have a math.js file that defines a math module. Well, Math.js is going to write this:

Math.js

Define (function () {

var add = function (x, y) {

return x+y;

};

return {

Add:add
};

});

The loading method is as follows:

Main.js

Require ([' math '], function (math) {

Alert (Math.add ());

});

If the module also relies on other modules, then the first parameter of the Define () function must be an array that indicates the dependency of the module.

define ([' mylib '], function (mylib) {

function foo () {

Mylib.dosomething ();

}

return {

Foo:foo

};

});

When the require () function loads the above module, the Mylib.js file is loaded first.

Vi. loading of non-canonical modules

In theory, require.js-loaded modules must be modules defined in accordance with the AMD specification, with the Define () function. But in fact, even though some popular libraries (such as jquery) are already in compliance with the AMD specification, more libraries don't fit. So, is require.js able to load non-canonical modules?

The answer is yes.

Such modules are used to define some of their characteristics before they are loaded with require (), using the Require.config () method.

For example, both underscore and backbone are not written in the AMD specification. If you want to load them, you must first define their characteristics.

Require.config ({

Shim: {

' Underscore ': {
Exports: ' _ '
},

' Backbone ': {
Deps: [' underscore ', ' jquery '],
Exports: ' Backbone '
}

}

});

Require.config () accepts a configuration object that, in addition to the paths property mentioned previously, has a shim property that is specifically designed to configure incompatible modules. Specifically, each module defines (1) The exports value (the output variable name), indicating the name of the external invocation of the module, and (2) An array of deps that indicates the dependency of the module.

For example, the plugin for jquery can be defined like this:

Shim: {

' Jquery.scroll ': {

Deps: [' jquery '],

Exports: ' JQuery.fn.scroll '

}

}

Seven, Require.js plug-in

Require.js also offers a range of plugins for specific functions.

The Domready plugin allows the callback function to run after the page DOM structure has been loaded.

Require ([' domready! '], function (DOC) {

Called Once the DOM is ready

});

The text and image plug-ins allow require.js to load texts and picture files.

Define ([

' Text!review.txt ',

' Image!cat.jpg '

],

function (Review,cat) {

Console.log (review);

Document.body.appendChild (CAT);

}

);

Similar plugins include JSON and Mdown, which are used to load JSON files and markdown files.

Modular programming of JavaScript

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.