JavaScript Modular programming (Note), javascript Modular

Source: Internet
Author: User

JavaScript Modular programming (Note), javascript Modular

I have always been familiar with JS. I recently encountered this problem, so I learned it online. I haven't fully understood it yet. I will post my notes first;

Chapter 1 JavaScript Modular programming

(1): module writing

Original Writing
// A module is a set of methods to implement specific functions. If you simply put different functions (and the variables that record the status) together, it is a module;
Function m1 (){
//...
}
Function m2 (){
//...
}
// The above functions m1 () and m2 () form a module, which can be called directly during use;
// Disadvantage: "contaminated" global variables; there is no guarantee that there will be no conflict with other modules of the variable name, and no direct relationship can be seen between module members;

2. Object writing

// Write the module as an Object, and all module members are put in this Object; var module = new Object ({_ count: 0, m1: function () {//...}, m2: function (){//...}}); // The above functions m1 () and m2 () are encapsulated in the module object; the attributes of this object are called directly during use; module. m1 (); // However, this write method exposes all module members and the internal status can be changed externally; module. _ count = 4;

3. Execute function writing immediately

Var module = (function () {var _ count = 0; var m1 = function (){//...}; var m2 = function () {}; return {m1: m1, m2: m2 };}) (); // use the preceding method, external Code cannot read the internal _ count variable; console.info (module. _ count); // undefined; // the above method is the basic method of writing JavaScript modules;

Quad-zoom Mode

// If the module is large, it must be divided into several parts, or a module must inherit from another module, it is necessary to adopt the "zoom mode"; var module = (function (mod) {mod. m3 = function (){//...}; return mod ;}) (module); // the above Code adds a new method m3 () to the module, and then returns the new module;

5-width zoom-in Mode

// In the browser environment, each part of the module is usually obtained from the Internet, and sometimes it cannot be known which part will be loaded first; // if the previous section is written, the first part of the execution may load a non-null object. In this case, we need to use the "wide zoom mode"; var module = (function (mod ){//... return mod;}) (window. module | {}); // compared with "zoom in mode", "wide zoom in mode" means that the parameter of "instant function execution" can be a null object;

Six input global variables

// Independence is an important feature of the module. It is best not to directly interact with other parts of the program within the module; // to call global variables within the module, other variable input modules must be explicitly input; var module = (function ($, YAHOO ){//...}) (jQuery, YAHOO); // The module above needs to use the jQuery library and YUI library, and the two libraries (actually two modules) are used as parameter input modules; // In addition to ensuring the independence of modules, the dependency between modules becomes obvious;

Chapter 2 JavaScript Modular programming (II): AMD specifications

Specification of Module 1
// Currently, there are two common JavaScript module specifications: CommonJS and AMD;

2. CommonJS
// Node. js uses the javascript language for server-side programming, which marks the birth of "JavaScript Modular programming;
// The node. js module system is implemented by referring to the CommonJS specification;
In CommonJS, there is a global method require () for Loading modules;
Var math = require ('Math'); // load the module;
Math. add (2, 3); // call the module method => 5;

3. browser Environment
// The code in the previous section has a big problem in the browser;
Var math = require ('Math ');
Math. add (2, 3 );
// Problem: math. add (2, 3) is executed only after loading of math. js such as require ('Math );
// The browser module cannot adopt "synchronous loading", but can only adopt "asynchronous loading"; ==> AMD;

Four AMD
AMD (Asynchronous Module Definition) Asynchronous Module Definition;
// The asynchronous loading module is used. The module loading does not affect the execution of subsequent statements. All statements dependent on this module are defined in a callback function,
// This callback function will run only after loading is complete;
// AMD also uses the require () statement to load the module, but it requires two parameters:
Require ([module], callback );
// Module: it is an array and its members are the modules to be loaded;
// Callback: the callback function after successful loading;
Require (['Math'], function (math ){
Math. add (2, 3 );
});
// The math. add () and math modules are not synchronized, And the browser will not be suspended; therefore, AMD is suitable for the browser environment;

Chapter 3 JavaScript Modular programming (III): Use of require. js
1. Why do I use require. js?
// Multiple js files need to be loaded in sequence;
// Disadvantage:
// 1. When loading, the browser will stop rendering the webpage. The more files are loaded, the longer the webpage will lose response;
// 2. Due to the dependency between js files, the loading sequence must be strictly ensured. When the dependency is complex, coding and maintenance become difficult;
// Therefore, require. js solves these two problems:
// 1. asynchronous loading of js files to prevent webpage response loss;
// 2. Manage dependencies between modules to facilitate code compilation and maintenance;

2. Loading of require. js
1. Load require. js
<Script scr = "js/require. js" defer async = "true"> </script>
// The async attribute indicates that the file needs to be asynchronously loaded to avoid webpage response loss. IE does not support this attribute and only supports defer. Therefore, defer is also written;
2. Load main. js
<Script src = "js/require. js" data-main = "js/main"> </script>
// The function of the data-main attribute is to specify the main module of the webpage program => main. js. This file will be first loaded by require. js;
// Because the default file Suffix of require. js is js, You Can abbreviated main. js as main;

Writing of main. js in the three main modules
1. If main. js does not rely on any other modules, JavaScript code can be directly written;
// Main. js
Alert ('Load successful! ');
2. If main. js depends on the module, use the require () function defined in AMD specifications;
// Main. js
Require (['lelea', 'leleb', 'lelec'], function (moduleA, moduleB, moduleC ){
//...
})
// The require () function receives two parameters:
// Parameter 1: array, indicating the dependent modules, that is, the three dependent modules of the main module;
// Parameter 2: callback function. After all the modules specified on the current plane are loaded successfully, the callback function is called. The loaded modules are passed in as parameters, these modules can be used inside the callback function;
// Require () asynchronously loads the module and the browser does not lose the response. The callback function specified by require () runs only after the previous modules are loaded successfully, solving the dependency problem;
Instance:
Require (['jquery ', 'underscore', 'backone'], function ($, _, backbone ){
//...
});

Four-module Loading
// Use the require. config () method to customize the module loading behavior;
// Require. config () is written in the header of the main module (main. js;
// The parameter is an object. The paths attribute of this object specifies the loading path of each module;
// Set the file default for the following three modules and a directory for main. js;
Require. config ({
Paths :{
"Jquery": "jquery. min ",
"Underscore": "underscore. min ",
"Backbone": "backbone. min"
}
});

// If the loaded module and the main module are not in the same directory, specify the path one by one;
Require. config ({
Paths :{
"Jquery": "lib/jquery. min ",
"Underscore": "lib/underscore. min ",
"Backbone": "lib/backbone. min"
}
});
// Or directly change the base Directory (baseUrl)
Require. config ({
BaseUrl: "js/lib ",
Paths :{
"Jquery": "jquery. min ",
"Underscore": "underscore. min ",
"Backbone": "backbone. min"
}
});

// If the module is on another host, you can specify its URL directly.
Require. config ({
Paths :{
"Jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"
}
});
// Require. js requires that each module be a separate js file. In this way, if multiple modules are loaded, multiple HTTP requests will be sent, affecting the loading speed of webpages;
// Therefore, require. js provides an optimization tool. After the module is deployed, you can use this tool to merge multiple modules into one file to reduce the number of HTTP requests;

Writing of AMD Module

// The modules loaded by require. js adopt AMD specifications. That is to say, the modules must be written in accordance with AMD regulations;
// 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;
// Define the math module in math. js
// Math. js
Define (function (){
Var add = function (x, y ){
Return x + y;
};
Return {
Add: add
};
});
// Load the math module in main. js
Require (['Math'], function (math ){
Alert (math. add (1, 1 ));
});
// If this module depends on other modules, the first parameter of the define () function must be an array to indicate the dependency of this module;
// Math. js
Define (['mylib '], function (myLib ){
Function foo (){
MyLib. doSomething ();
}
Return {
Foo: foo
};
});
// When the require () function loads the above module, the myLib. js file will be loaded first;

6. Load nonstandard modules

// Load nonstandard modules. Before loading with require (), use the require. config () method to define some of their features;
Require. config ({
Shim :{
'Underscore ':{
Exports :'_'
},
'Background ':{
Deps: ['underscore ', 'jquery'],
Exports: 'backone'
}
}
});
// Require. config () receives a configuration object. In addition to the paths attribute mentioned earlier, this object also has a shim attribute, which is used to configure incompatible modules;
// (1). Define the deps array to indicate the dependency of the module;
// (2). Define the exports value (name of the output variable) to indicate the name of the module during external calls;
For example, jQuery plug-in
Shim :{
'Jquery. scroll ':{
Deps: ['jquery '],
Exports: 'jquery. fn. scroll'
}
};

Seven require. js plug-ins

1. domready: enables the callback function to run after the DOM structure of the page is loaded;
Require (['domainready! '], Function (doc ){
// Called once the DOM is ready;
})
2. text and image: Allow require. js to load text and image files;
Define (['text! Review.txt ', 'image! Cat.jpg '], function (review, cat ){
Console. log (review );
Document. body. appendChild (cat );
});

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.