JAVASRIPT Module Specification-AMD specification and CMD specification introduction

Source: Internet
Author: User
Tags define definition

Javasript modularity before understanding the Amd,cmd specification, it is necessary to understand briefly what is modular and modular development? Modularity refers to the systematic decomposition of a problem in order to solve a complex problem or a series of mixed problems, according to a sort of thinking. Modularity is a way of dealing with complex systems that break down into manageable modules that are more logical and maintainable in code structures. Imagine a huge system code, how meaningful it is for software to be integrated and optimized to be segmented into highly logical modules.     For the software industry: The complexity of decoupling software systems makes it possible to manage, develop, and maintain a "rational and predictable" system, no matter how large. Some of the modules are defined as: Modularity is a property of a software system that is decomposed into a set of high-cohesion, low-coupling modules. Then in the ideal state we only need to complete their own part of the core business logic code, other aspects of the dependency can be directly loaded by the user has already written the module to use. First, since it is a modular design, the ability to act as a modular system: 1.    Defines the encapsulated module.    2. Define the dependencies of the new modules on other modules.     3. Can support the introduction of other modules. Well, thought has, then always have something to build a modular system of norms, otherwise all kinds of module loading will only make the bureau more chaotic. Then in JavaScript there are some non-traditional module development methods of the Specification COMMONJS module specification, AMD (asynchronous module definition), CMD (Common module definition) and so on. AMD and Requirejs AMDAsynchronous module definition, in vernacular speaking is the asynchronous module definition, for Jser, async is no longer familiar with the word, all modules will be loaded asynchronously, module loading does not affect the subsequent statement run.     All statements that depend on certain modules are placed in the callback function. The AMD specification defines a function that is either a free variable or a global variable define.

define (ID?, dependencies, factory);    

AMD Spec Https://github.com/amdjs/amdjs-api/wiki/AMD The first parameter ID is a string type, which represents the module ID, which is an optional parameter. If it does not exist, the module identity should be defined by default as the identity of the requested script in the loader.    If present, then the module ID must be a top-level or an absolute identity.    The second parameter, dependencies, is an array literal that the current module relies on to identify the module that has been defined by the module.     The third argument, factory, is a function or an object that needs to be instantiated. Create modules identified as alpha, dependent on require, export, and modules identified as Beta
Define ("Alpha", ["require", "exports", "beta"], function (require, exports, beta) {    export.verb = function () {        re Turn Beta.verb ();        Or:        return require ("beta"). verb ();    }});

An asynchronous module that returns the literal of an object

define (["alpha"], function (Alpha) {    return {        verb:function () {            return Alpha.verb () + 1;        }}    );

No-dependency modules can be defined directly using object literals

Define ({    add:function (x, y) {        return x + y;    }});

Similar to the CommonJS method definition

Define (function (Require, exports, module) {    var a = require (' a '),          B = require (' B ');    Exports.action = function () {};} );

  

Require ();

Require API describes the Https://github.com/amdjs/amdjs-api/wiki/require in the AMD specification require function differs from the require in general Commonjs. Because dynamic detection of dependencies makes loading asynchronous, there is a strong demand for callback-based require.

require of local and global

Local require need to pass in the require in the Define factory function in AMD mode.
define ([' Require '], function (require) {  //...}); O R:define (function (Require, exports, module) {  //...});

  

Local require require other specific APIs to implement. The global require function is the only variable in the global scope, like define. Global require is not a specification requirement, but if you implement a global require function, then it needs to have the following qualification as the local require function: 1.    The module identity is considered absolute, not relative to the other module identity. 2. Only in asynchronous cases, require's callback method is used as an interactive operation.    Because he could not load the module from the top level with require (String) in the case of synchronization. Dependency-dependent APIs will start the module loading. If you need to have multiple, interoperable loaders, the global reqiure should be loaded with the top-level module instead.
Require (String) define (function (require) {    var a = require (' a ');//Load Module A}); require (Array, function) define (functio N (require) {    require ([' A ', ' B '], function (b) {///load module a B using        //dependent on the run code of a B module    }); Require.tourl (URL) define (function (require) {    var temp = Require.tourl ('./temp/a.html ');//Load page});

  

Amdjs's API Https://github.com/amdjs/amdjs-api/wiki RequirejsOfficial website Http://www.requirejs.org/API http://www.requirejs.org/docs/api.html Requirejs is a front-end modular management tool library that complies with AMD's specifications and is the author of AMD The standard founder James Burke.     So it's not too requirejs to say that the AMD specification is being explained. The basic idea of requirejs is that a function is used to load all required or dependent module implementations, and then return a new function (module), all of our business code about the new module is inside the function, and the inside of it can use the modules that have been loaded since.

<script data-main= ' scripts/main ' src= ' scripts/require.js ' ></script>

  

Then scripts under the Main.js is the specified main code script file, all the dependent module code files will start from the file asynchronous loading into execution.   defined is used to define modules, Requirejs requires each module to be placed in a separate file. Separate modules and non-independent modules are classified according to whether or not other modules are dependent. 1. Independent module, not dependent on other modules. Direct definition:
    1. Define ({
    2. Method1:function () {},
    3. Method2:function () {}
    4. });
is also equivalent to

    1. Define (function () {
    2. return{
    3. Method1:function () {},
    4. Method2:function () {}
    5. }
    6. });
2. Non-standalone module, dependent on other modules.
    1. Define ([' Module1 ', ' module2 '], function (m1, m2) {
    2. ...
    3. });
Or:
    1. Define (function (require) {
    2. var m1 = require (' Module1 '),
    3. M2 = require (' module2 ');
    4. ...
    5. });


Simply looking at the implementation of the REQUIREJS, its require implementation is simply to take the function string and then extract the module name after require, put it into the dependency relationship.   require method call moduleWhen require calls a module, its parameters are similar to define.
    1. Require ([' foo ', ' bar '], function (foo, bar) {
    2. Foo.func ();
    3. Bar.func ();
    4. } );
Executes the callback function implementation procedure after loading Foo and bar two modules. Of course, as in the previous example, the Require call module is made inside the Define definition module
    1. Define (function (require) {
    2. var m1 = require (' Module1 '),
    3. M2 = require (' module2 ');
    4. ...
    5. });
Define and require these two definition modules, calling the module method is called AMD mode, the definition module is clear, will not pollute the global variables, clearly show the dependency. The AMD mode can be used in a browser environment and allows asynchronous loading of modules or dynamically loading modules on demand.

CMD and Seajs CMDIn cmd, a module is a file in the form of: define (factory);The global function, define, is used to define the module.    The parameter factory can be a function, or it can be an object or a string.     When factory is an object, a string, the interface that represents the module is the object, the string. To define a JSON data module:
    1. Define ({"foo": "Bar"});
To define a template module through a string:
    1. Define (' This is {data}}. ');
When factory is a function, the method of constructing the module is represented, and the interface provided by the module can be obtained by executing the construction method.
    1. Define (function (Require, exports, module) {
    2. Module code
    3. });


define (ID?, Deps, Factory);Define can also accept more than two parameters, the string ID is the module identifier, and the array deps is the module dependency:
    1. Define (' module ', [' Module1 ', ' module2 '], function (require, exports, module) {
    2. Module code
    3. } );
It differs from the AMD spec usage. requireIs the first parameter of a factory.    require (ID); Accept the module identity as the only parameter used to obtain the interfaces provided by the other modules:
    1. Define (function (require, exports) {
    2. var a = require ('./a ');
    3. A.dosomething ();
    4. });
Require.async (ID, callback?); Require is performed synchronously, and the required asynchronous load module can be loaded using Require.async:
    1. Define (function (Require, exports, module) {
    2. Require.async ('. A ', function (a) {
    3. A.dosomething ();
    4. });
    5. });
The Require.resolve (ID) can use the path mechanism inside the module to return the module path without loading the module. exportsis the second parameter of factory, which is used to provide a module interface to the outside.
    1. Define (function (require, exports) {
    2. Exports.foo = ' Bar '; Out-of-the-supply properties
    3. Exports.do = function () {}; Methods available out-of-the-way
    4. });
Of course, you can also use return to provide an interface directly to the outside.
    1. Define (function (require, exports) {
    2. return{
    3. Foo: ' Bar ',//out-of-the-supply properties
    4. Do:function () {}//outward-available method
    5. }
    6. });
You can also simplify the form of direct object literals:
    1. Define ({
    2. Foo: ' Bar ',//out-of-the-supply properties
    3. Do:function () {}//outward-available method
    4. });


As you should note in Nodejs, the way is wrong:
    1. Define (function (require, exports) {
    2. Exports = {
    3. Foo: ' Bar ',//out-of-the-supply properties
    4. Do:function () {}//outward-available method
    5. }
    6. });


Need to do this.
    1. Define (function (Require, exports, module) {
    2. Module.exports = {
    3. Foo: ' Bar ',//out-of-the-supply properties
    4. Do:function () {}//outward-available method
    5. }
    6. });
An incoming object reference can add a property, and once a new object is assigned, the value passed in will invalidate the object reference. At the beginning, exports was a reference to Module.exports, and all behavior was only factory on this reference, and after assigning a new object, the reference was broken, and exports was just a new object reference. It makes no sense for factory to make a mistake. Moduleis the third parameter of factory, which is an object that stores some properties and methods associated with the current module.        Module.id is the unique identifier for the module.        Module.uri the absolute path of the module according to the path parsing rules of the module system.        Module.dependencies represents the dependency of the module. Module.exports the interface provided externally by the current module.

SeajsOfficial website Http://seajs.org/docs/API Quick Reference https://github.com/seajs/seajs/issues/266
Sea.js Core Features: 1.        Follow the CMD specification, with Nodejs-like writing module code.    2. Rely on automatic loading, the configuration is clear and concise. Compatible with Chrome 3+,firefox 2+,safari 3.2+,opera 10+,ie 5.5+. Seajs.useUsed to load one or more modules in a page
    1. Loading a module
    2. Seajs.use ('./a ');
    3. Load module, execute callback when loading is complete
    4. Seajs.use ('. A ', function (a) {
    5. A.dosomething ();
    6. });
    7. Load multiple modules to execute callbacks
    8. Seajs.use ('./a ', './b '],function (A, b) {
    9. A.dosomething ();
    10. B.dosomething ();
    11. });
The use of define and require is basically an example of the CMD specification.   where is the difference between AMD and CMD?  Looking at the above Amd,requirejs and CMD, Seajs's brief introduction will be a little vague, the total feeling is more similar.     Because like Requirejs it is not just pure amd inherent ideas, it is also the idea of a CMD specification, but is recommended AMD Standard way, SEAJS is the same.    Here is Yuber's explanation for the difference between AMD and CMD: AMD is the normalized output of the module defined by REQUIREJS during the promotion process.     CMD is the normalized output of the module defined by SEAJS in the process of generalization.      Similar to the CommonJS modules/2.0 specification, is bravojs in the promotion process of the module definition of standardized output still a lot??    These specifications are intended for the modular development of JavaScript, especially on the browser side.      At present, the implementation of these specifications can achieve the purpose of browser-side modular development. Difference: 1. For dependent modules, AMD is executed ahead of time, and CMD is deferred execution. However, starting from 2.0, Requirejs is also changed to be deferred (depending on the way it is written and handled differently).     CMD respected as lazy as possible. 2. CMD is highly dependent on the nearest, AMD is highly dependent on the predecessor. Look at the code:
    1. //CMD
    2. define (function (require, exports, module)  {
    3.     var a = require ('./a ')
    4.     a.dosomething ()
    5.     //omit 100 lines here
    6.     var b = require ('./b ')  //dependencies can be written near
    7.     b.dosomething ()
    8.     //...
    9. })
    10. //AMD The default recommendation is
    11. define (['./a ',  './b '], function (a, b)  { / /dependencies must be written in the first place
    12.     a.dosomething ()
    13.     //omit 100 lines here
    14.     b.dosomething ()
    15.     //...
    16. })
While AMD supports the syntax of CMD, it also supports passing require as a dependency, but Requirejs's author defaults to the preferred notation, which is the default definition of the module in the official document. 3. AMD's API defaults to one when multiple uses, the CMD API is strictly differentiated, advocating a single responsibility. For example, AMD, require global require and local require, are called require. In CMD, there is no global require, but according to the completeness of the module system, provide seajs.use to realize the loading and starting of the module system.      CMD, each API is simple and pure. 4. There are also some details of the difference, the specific definition of the specification is good, not much to say. In addition, SEAJS and Requirejs differences, you can refer to: https://github.com/seajs/seajs/issues/277 SummaryThis article is mainly about the AMD cmd specification, by the way a brief description of Requirejs and Seajs. Speaking more generally, the following extended reading can better help you understand modularity and individual specifications. Extended reading:AMD Specification Document Https://github.com/amdjs/amdjs-api/wiki/AMD
Amdjs Require interface documentation Https://github.com/amdjs/amdjs-api/wiki/require
Amdjs Interface Document &NBSP;HTTPS://GITHUB.COM/AMDJS/AMDJS-API/WIKIREQUIREJS official website Interface Document  http://www.requirejs.org/docs/ The value of api.html   modular system  https://github.com/seajs/seajs/issues/240 Front-end modularization development  https://github.com/ seajs/seajs/issues/547 Front-end modular development that point of History  https://github.com/seajs/seajs/issues/588cmd Module definition Specification  https:// GITHUB.COM/SEAJS/SEAJS/ISSUES/242SEAJS API Quick Reference  https://github.com/seajs/seajs/issues/266 from CommonJS to Sea.js  https://github.com/seajs/seajs/issues/269    requirejs and AMD specification  http:// JAVASCRIPT.RUANYIFENG.COM/TOOL/REQUIREJS.HTML&NBSP;COMMONJS Specification  http://javascript.ruanyifeng.com/nodejs/ Commonjs.htmljavascript Modular Programming  http://www.ruanyifeng.com/blog/2012/10/javascript_module.htmljavascript Modular Programming  http://www.ruanyifeng.com/blog/2012/10/asynchronous_module_definition.html know what the difference between  AMD and CMD is?  http://www.zhihu.com/question/20351507  javascript Modular Development-COMMONJS specification  http:// Www.feeldesignstudio.com/2013/09/javascript-module-pattern-commonjs 
JavaScript Modular Development-AMD spec HTTP://WWW.FEELDESIGNSTUDIO.COM/2013/09/JAVASCRIPT-MODULE-PATTERN-AMD

Modular Design Http://baike.baidu.com/view/189730.htm
Modular http://baike.baidu.com/view/182267.htm

JAVASRIPT Module Specification-AMD specification and CMD specification introduction

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.