JavaScript Modular Programming (notes) _javascript tips

Source: Internet
Author: User
Tags jquery library

JS has always been a smattering of knowledge, recently encountered this aspect of the problem, so on the internet to learn a bit, and now do not fully understand, first posted notes;

The first chapter JavaScript modular programming

(i): the formulation of modules

A primitive writing
//module is a set of methods for implementing a particular function; Simply put the different functions (and the variables of the record state) together, even if it is a module;
function M1 () {
// ...
}
function m2 () {
// ...
}
The functions above are M1 () and M2 () to form a module, which can be invoked directly when used.
Disadvantage: "Pollution" of the global variable; There is no guarantee that variable names conflict with other modules, and there is no direct relationship between module members;

The writing of two objects

Write the module as an object and all the module members are placed inside the object;
  var module = new Object ({
    _count:0,
    m1:function () {
      //...
    },
    m2:function () {
      //...
    }}
  ) ;
The above functions, M1 () and M2 (), are encapsulated in the module object, and the object's properties
  are called directly when used; MODULE.M1 ();
However, such a writing will expose all module members, the internal state can be externally rewritten;
  Module._count = 4;

Three to execute function writing immediately

  var module = (function () {
    var _count = 0;
    var m1 = function () {
      //...
    };
    var m2 = function () {

    };
    return {
      m1:m1,
      m2:m2
    };
  }) ();
Using the above notation, the external code cannot read the internal _count variable;
  Console.info (Module._count); undefined;
The above writing is the basic JavaScript module;

Four amplification mode

If the module is large, it must be divided into several parts, or a module needs to inherit another module, then it is necessary to use the "magnification mode";
  var module = (function (mod) {
    mod.m3 = function () {
      //...
    };
    return mod;
  }) (module);
The above code adds a new method M3 () for the module module, and then returns the new module modules;

Five wide magnification mode

In a browser environment, parts of a module are usually retrieved from the web, and sometimes it is impossible to know which part will be loaded first;
If the previous section of the wording, the first part of the execution may load a non-existent empty object, at this time to adopt a "wide magnification mode";
  var module = (function (mod) {
    //...
    return mod;
  }) (Window.module | | {});
In contrast to "magnification mode", the "wide magnification mode" is the "execute function immediately" parameter can be an empty object;

Six input global variables

Independence is an important feature of the module, it is best not to interact with other parts of the program directly;
In order to call global variables inside a module, other variables must be explicitly input into the module;
  var module = (function ($,yahoo) {
    //...
  }) (Jquery,yahoo);
The module above needs to use the jquery library and Yui Library, the two libraries (in fact, two modules) as a parameter input module;
In addition to ensuring the independence of the module, it makes the dependencies between the modules become obvious;

Chapter II JavaScript modular Programming (II): AMD specifications

Specification for a module
At present, there are two kinds of standard JavaScript modules: Commonjs and AMD;

Two Commonjs
Node.js uses JavaScript language for server-side programming, which marks the formal birth of "JavaScript modular Programming";
The modular system of Node.js is realized by reference to COMMONJS specification;
In Commonjs, there is a global method require () for loading modules;
var math = require (' math '); Loading module;
Math.add (2,3); Calling the module method =>5;

Three browser environment
The code in the previous section runs in a browser with a large problem;
var math = require (' math ');
Math.add (2,3);
Problem: The Require (' math ') must be math.js loaded to complete before the execution of Math.add (2,3);
Therefore, the browser module, can not adopt "synchronous loading", only "asynchronous loading";==>amd;

Four AMD
AMD (asynchronous module definition) asynchronous module definition;
With the asynchronous loading module, the load of the module does not affect the operation of the following statements, all the statements that depend on this module are defined in a callback function,
After the load is completed, the callback function will not run;
AMD also uses the Require () statement to load the module, but it requires two parameters:
Require ([module],callback);
Module: is an array in which the members are the modules to be loaded;
Callback: Is the callback function after the successful loading;
Require ([' Math '],function (math) {
Math.add (2,3);
});
Math.add () and the math module loading is not synchronized, the browser will not be suspended animation, so, AMD is more suitable for the browser environment;

Chapter III JavaScript modular Programming (III): the use of require.js
One why use Require.js
Need to load multiple JS files sequentially;
Disadvantages:
1. When loading, the browser will stop the Web page rendering, the more loading files, the longer the page will lose the response time;
2. Because of the dependencies between JS files, we must strictly guarantee the loading sequence, when the dependency relationship is very complex, code writing and maintenance will become difficult;
So Require.js solves these two problems:
1. Implement the asynchronous loading of JS files to avoid web page loss of response;
2. Manage the dependencies between the modules, easy to write and maintain the code;

Loading of two Require.js
1. Loading require.js
<script scr= "js/require.js" defer async= "true" ></script>
The async attribute indicates that the file needs to be loaded asynchronously to prevent the Web page from losing its response; IE does not support this attribute, only supports defer, so write defer also;
2. Loading Main.js
<script src= "Js/require.js" data-main= "Js/main" ></script>
The function of the Data-main property is to specify the main module of the Web page program =>main.js, the file will be first loaded by require.js;
Because require.js default file suffix name is js, so you can main.js abbreviated to main;

The main.js of the three main modules is
1. If Main.js does not rely on any other modules, you can write JavaScript code directly;
//Main.js
     Alert (' Load succeeded! ');
2. If Main.js relies on modules, then use the Require () function defined by the AMD specification;
//Main.js
    require ([' Modulea ', ' Moduleb ', ' Modulec '],function (Modulea,moduleb,modulec) {
       //...
   }) The
//require () function receives two parameters:
//Parameter one: An array representing the dependent modules, that is, the three modules that the main module relies on;
//Parameter two: The callback function, which is called when the module specified by the current plane is successfully loaded, and the loaded module passes the function as a parameter So that these modules can be used within the callback function;
//require () The module is loaded asynchronously, the browser does not lose its response, and its specified callback function, which only works after the previous module has been loaded successfully, solves the dependency problem;
Instance:
    require ([' jquery ', ' underscore ', ' backbone '],function ($,_,backbone) {
        //...
   });

Four loading of modules
//using the Require.config () method, the loading behavior of the module can be customized;
Require.config () is written on the head of the main module (main.js);
The parameter is an object, the paths attribute of the object specifies the loading path of each module;
Set the following three modules for file defaults and main.js in a directory;
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 at a A.
Require.config ({
paths:{
"jquery": "Lib/jquery.min",
"Underscore": "Lib/underscore.min",
"Backbone": "Lib/backbone.min"
}
});
or change the base directory directly (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 also specify its URL directly
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 you load multiple modules, you will send multiple HTTP requests, will affect the speed of the Web page loading;
Therefore, Require.js provides an optimization tool that, when the module is deployed, can use the tool to merge multiple modules into a single file, reducing the number of HTTP requests;

The formulation of five AMD modules

Require.js loaded modules, using AMD specifications, that is, the module must be written in accordance with AMD requirements;
Specifically, the module must be defined by a specific define () function, and if a module does not rely on other modules, it can be defined directly 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 the module also relies on other modules, then the first parameter of the Define () function must be an array indicating the dependency of the 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 is loaded first;

Six loads of non-standard modules

Loading non-standard modules, before using require () to load, first use the Require.config () method to define some of their characteristics;
Require.config ({
shim:{
' Underscore ': {
Exports: ' _ '
},
' Backbone ': {
deps:[' underscore ', ' jquery '],
Exports: ' Backbone '
}
}
});
Require.config () receives a configuration object that, in addition to the previously mentioned paths attribute, has a shim attribute that is specifically configured to configure incompatible modules;
(1). Defines the Deps array, indicating the dependency of the module;
(2). Defines the exports value (the output variable name) indicating the name of the module outside the call;
For example: jquery's Plugin
shim:{
' Jquery.scroll ': {
deps:[' jquery '],
Exports: ' JQuery.fn.scroll '
}
};

Seven Require.js Plug-ins

1.domready: You can have the callback function run after the page DOM structure is loaded;
Require ([' domready! '],function (DOC) {
Called Once the DOM is ready;
})
2.text and Image: Allows Require.js to load text and picture files;
define ([' Text!review.txt ', ' image!cat.jpg '],function (review,cat) {
Console.log (review);
Document.body.appendChild (CAT);
});

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.