Detailed JavaScript modular development _javascript Skills

Source: Internet
Author: User
Tags aliases define function script tag

What is modular development?

In the front-end development, as long as in the script tag embedded in dozens of hundreds of lines of code can achieve some basic interactive effect, later JS received attention, the application is also widely up, Jquery,ajax, NODE.JS,MVC,MVVM and so on also make front-end development attention, but also make the front-end project more and more complex, however, JavaScript does not provide any obvious help to the organization code, not even the concept of the class, let alone modules (module), then what is the module?

A module is to implement a specific function of the file, with the module, we can more easily use other people's code, want what function, loaded what module. Module development needs to follow certain specifications, otherwise it will all be messed up.

According to the AMD specification, we can use the define to define the module and use the Require to invoke the module.

At present, the prevailing JS module specifications are mainly two kinds: Commonjs and AMD.

AMD Specifications

AMD is asynchronous module definition, the Chinese name is "asynchronous module definition" meaning. It is a modular development in the browser side of the specification, server-side specifications are COMMONJS

The module will be loaded asynchronously, and the module load does not affect the running of the subsequent statements. All statements that depend on certain modules are placed in the callback function.

AMD is the normalized output of the module defined by REQUIREJS during the promotion process.

Define () function

The AMD specification defines only one function define, which is a global variable. The function is described as:

Define (ID, dependencies, Factory);

Parameter description:

ID: Refers to the name of the module in the definition, optional; If this parameter is not supplied, the name of the module should default to the name of the specified script requested by the module loader. If this argument is provided, the module name must be "top-level" and absolute (not allowed relative names).

Dependent dependencies: Is the literal amount of an array that the current module relies on, identified by module-defined modules.
The dependent parameter is optional, and if this argument is omitted, it should default to [Require, exports, module]. However, if the length property of the factory method is less than 3, the loader chooses to invoke the factory method with the number of parameters specified in the function's Length property.

Factory method Factory, the module initializes the function or object to be executed. If it is a function, it should only be executed once. If it is an object, this object should be the output value of the module.

Format of module name

Module names are used to uniquely identify the modules in the definition, and they are also used in the dependency array:

The module name is a string of meaningful words separated by a forward slash
The word must be in hump form, or ".", "."
The module name does not allow the form of a file name extension, such as ". JS"
The module name can be "relative" or "top-level." If the first character is "." or ".." is the relative module name
The top-level module name is parsed from the conceptual module of the root namespace
Module parsing of the relative module name written and invoked from "require"

Using require and exports

Create a module named "Alpha" with Require,exports, and a module called "Beta":

 Define ("Alpha", ["require", "exports", "beta"], function (require, exports, beta) {
    exports.verb = function () {
      R Eturn Beta.verb ();
      Or: Return
      require ("beta"). verb ();
    }
  });

Require API Introduction: Https://github.com/amdjs/amdjs-api/wiki/require

AMD specification Chinese version: https://github.com/amdjs/amdjs-api/wiki/amd-(%e4%b8%ad%e6%96%87%e7%89%88)

At present, the realization of AMD's library has Requirejs, curl, Dojo, nodules and so on.

COMMONJS specification

COMMONJS is the specification of the server-side module, which Node.js adopted. Node.js first adopted the concept of JS modularity.

According to the COMMONJS specification, a separate file is a module. Each module is a separate scope, that is, a variable defined within the module cannot be read by another module unless it is defined as a property of the global object.

The best way to output a module variable is to use the Module.exports object.

var i = 1;
var max =;

Module.exports = function () {for
 (i-= 1; i++ < Max;) {
  Console.log (i);
 }
 Max *= 1.1;

The code above uses a Module.exports object to define a function that is the bridge between the module's external and internal communications.

The load module uses the Require method, which reads a file and executes it, and finally returns the Module.exports object inside the file.

COMMONJS Specification: http://javascript.ruanyifeng.com/nodejs/commonjs.html

Requirejs and Seajs

Requirejs was created by James Burke, and he was also the founder of AMD specifications.

The Define method is used to define modules, and Requirejs requires each module to be placed in a separate file.

Requirejs and Sea.js are modular loaders, advocating the concept of modular development, the core value is to make JavaScript modular development becomes simple and natural.

The biggest difference between Seajs and Requirejs:

Seajs's attitude towards the module is lazy execution, while Requirejs's attitude towards the module is pre-execution

Don't understand? Look at this illustrated article: http://www.douban.com/note/283566440/

Requirejs api:http://www.requirejs.cn/docs/api.html

Usage of Requirejs: http://www.ruanyifeng.com/blog/2012/11/require_js.html

Why do you use Requirejs?

Imagine if a page has a lot of JS files, then the browser download the page will first load the JS file, thus stopping the Web page rendering, if the more files, the browser may lose its response. Secondly, to ensure the dependence of JS files, the most dependent modules (files) to be put in the final load, when the dependency is very complex, code writing and maintenance will become difficult.

Requirejs was born to solve these two problems:

(1) To realize the asynchronous loading of JS files to avoid web page loss of response;
(2) Management of the dependencies between modules, easy to write code and maintenance.

Requirejs File Download: http://www.requirejs.cn/docs/download.html

AMD and CMD

CMD (Common module definition) generic module definition. The specification clearly introduces the basic writing format and basic interaction rules of the module. The specification is developed at home. AMD is dependent on the predecessor, and CMD is loaded on demand.

In the CMD specification, a module is a file. The code is written in the following format:

Define (factory);

When factory is a function, the representation is the construction method of the module. The construction method is executed, and the interface provided by the module can be obtained. When the factory method executes, the default passes in three parameters: require, exports, and module:

Define (function (Require, exports, module) {
 //module Code
});

Require is a parameter that can be imported into other modules, and export can derive some of the properties and methods within the module.

CMD specification Address: https://github.com/seajs/seajs/issues/242

AMD is requirejs in the promotion process of the modular definition of the standardized output.
CMD is the normalized output of the module defined by SEAJS in the process of popularization.

For dependent modules, AMD is in advance, and CMD is deferred execution.

AMD: Ahead of time (asynchronous loading: Dependent execution first) + deferred execution
CMD: Delay execution (run to load, execute according to order)
CMD is highly reliant on proximity, AMD is highly reliant on relying on predecessors. Look at the following code:

CMD
define (function (Require, exports, module) {
var a = require ('. a ')
a.dosomething ()
//Here omit 100 lines C5/>var B = require ('./b ')//dependencies can be written near the
b.dosomething ()
//... 
})

AMD defaults recommend
define (['. a ', './b '], function (A, B) {//Reliance must be written at the beginning
a.dosomething ()
//Here omit 100 lines
B.D Osomething ()
...
})

Another difference is:

AMD:API differs depending on the scope of use, but uses the same API interface
CMD: Single responsibility for each API
AMD's advantages are: asynchronous parallel loading, under the AMD specification, while asynchronous loading is not an error.
The mechanism of CMD is different, this kind of loading method will produce error, if can standardize module content form, also can

jquery1.7 the above version will be automatically modular to support AMD mode: mainly using the Define function, Sea.js is the COMMONJS specification, but uses the define to define the module
So jquery is automatically modular.

Seajs.config ({'
base ': '/',
' alias ': {
  ' jquery ': ' jquery.js '//define jquery file
}
});

The Define function is similar to AMD's define:

Define (function (require, exports, module{
   //First load jquery module
   var $ = require (' jquery ');
   The jquery object is then passed to the plug-in module
   require ('./cookie ') ($);
   Start using the $.cookie method
});

How to use Sea.js?

Introduction of Sea.js Libraries

How to become a module?

Define

3. How do I call the module?

-exports
-sea.js.use
4. How do I rely on modules?

-require

<script type= "Text/javascript" >
    define (Function (require,exports,module) {
      //exports: external interface
      / /requires: Dependent interface
      require ('./test.js ');//If the address is a module, then the Require return value is the exports in the module
    )
</script >

Sea.js Development Example

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

A colleague

A colleague written by Main.js:

define (function (require,exports,module) {
  var oinput = document.getElementById (' input1 ');
  var oDiv1 = document.getElementById (' Div1 ');
  var oDiv2 = document.getElementById (' div2 ');
  var oDiv3 = document.getElementById (' Div3 ');

  Require ('./drag.js '). Drag (oDiv3);
  Oinput.onclick = function () {
    oDiv1.style.display = ' block ';
    Require ('./scale.js '). scale (ODIV1,ODIV2);

    Require.async ('./scale.js ', function (ex) {
      ex.scale (ODIV1,ODIV2);
    })
  }
);

B Colleague

B colleague wrote Drag.js:

define (function (require,exports,module) {
  
  function drag (obj) {
    var disx = 0;
    var disy = 0;
    Obj.onmousedown = function (ev) {
      var ev = EV | | window.event;
      DISX = Ev.clientx-obj.offsetleft;
      Disy = Ev.clienty-obj.offsettop;
      
      Document.onmousemove = function (ev) {
        var ev = EV | | window.event;


         var L = require ('./range.js '). Range (EV.CLIENTX-DISX, document.documentelement.clientwidth-obj.offsetwidth, 0); 
   
    var T = require ('./range.js '). Range (Ev.clienty-disy, document.documentelement.clientheight-obj.offsetheight, 0); 
    obj.style.left = L + ' px ';
        Obj.style.top = T + ' px ';
      Document.onmouseup = function () {
        document.onmousemove = null;
        Document.onmouseup = null;
      return false;}
  
  Exports.drag = drag;//External Supply Interface
  
});
   

C Colleague

C colleague written by Scale.js:

define (function (require,exports,module) {
  
  
  function scale (OBJ1,OBJ2) {
    var disx = 0;
    var disy = 0;
    var disw = 0;
    var DisH = 0;
    
    Obj2.onmousedown = function (ev) {
      var ev = EV | | window.event;
      DISX = Ev.clientx;
      Disy = Ev.clienty;
      DISW = Obj1.offsetwidth;
      DisH = obj1.offsetheight;
      
      Document.onmousemove = function (ev) {
        var ev = EV | | window.event;
        
        var W = require ('./range.js '). Range (Ev.clientx-disx + DISW, MB);
        var H = require ('./range.js '). Range (Ev.clienty-disy + disH, MB);
        
        Obj1.style.width = W + ' px ';
        Obj1.style.height = H + ' px ';
      Document.onmouseup = function () {
        document.onmousemove = null;
        Document.onmouseup = null;
      return false;}
  
  Exports.scale = scale;
  
});

D Colleague

D Colleague's range.js--limit drag range

  define (function (require,exports,module) {
    
    function range (inum,imax,imin) {
      
      if ( Inum > Imax) {return
        imax;
      }
      else if (Inum < imin) {return
        imin;
      }
      else{return
        inum
      }
      
    }
    
    Exports.range = range;
    
  });

Requirejs Development Example

Require.config is used to define aliases and to configure aliases under the Paths property. Then pass Requirejs (parameter one, parameter two); parameter one is an array, pass in the module name that we need to refer to, the second parameter is a callback function, the callback function passes a variable, replace the module that just introduced.

Main.js file

Alias configuration
requirejs.config ({
  paths: {
    jquery: ' jquery.min '//can omit. js
  }
});
The module is introduced with variable $ to represent
the jquery module Requirejs ([' jquery '], function ($) {
  $ (' body '). CSS (' background-color ', ' red ');
});

The Introduction module can also write only require (). The REQUIREJS is defined by the Define () definition module, the same as the parameters defined. Outside of the methods and variables in this module are inaccessible and can only be returned by return.

Define Module

define ([' jquery '], function ($) {//Introducing jquery module return
  {
    add:function (x,y) {return
      x + y;}};
});

Name the module Math.js save.

Main.js Introduction Module method

Require ([' jquery ', ' math '], function ($,math) {
  console.log (Math.add (10,100));//110
});

No Reliance

If the defined module does not depend on other modules, you can:

Define (function () {return

  {
    name: ' Trigkit4 ', age
    : '
  }} '
);

AMD recommended style by returning an object as a module object, COMMONJS's style is to expose the object of the module by assigning values to module.exports or exports properties.

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.