Modular JavaScript design mode (i)

Source: Internet
Author: User

In the world of extensible JavaScript, assuming we say that an application is modular (modular), it usually means that it is composed of a series of highly decoupled, different functional fragments stored in the module.

In case of possible. Through a dependency. Loose coupling makes the application easier to maintainability. Assuming that this is achieved effectively, it is very easy to understand how part of the impact has a part.


The overall goal of the asynchronous module definition (AMD) is to provide a modular approach to JavaScript. For developers to use. Born in the Dojo development experience using Xhr+eval. Supporters of this format hope to avoid any future solutions that are affected by shortcomings in past solutions. The AMD module format itself is a recommendation for defining modules, and its modules and dependencies will be loaded asynchronously.

AMD started out as a draft specification for the COMMONJS module format, but the further development of such a format shifted to the Amdjs community (HTTPS://GITHUB.COM/AMDJS) because it did not reach a broad consensus.


First, the introduction of the module

There are two key concepts that are worth noting about AMD, which are define methods for module definitions and require methods for handling dependent loading. Try the method. Define is used to define a named or unnamed module:

Define (    module_id/* optional */,    [dependencies]/* optional */,    definition function/*function for instantiating the Module or object to instantiate a function of the modules or objects */)


The module_id is an optional number of references. It is usually only required if the non-AMD connection tool is used. When this parameter is omitted. We call this module non-anonymous (anonymous).

When using this anonymous module. The concept of module identity is dry to make it easier to avoid file names and code iterations. As the code becomes lighter, you can move it very easily to another location without having to alter the code itself or change its module ID.


Developers can execute the same code in multiple environments by using the AMD optimizer only, and the AMD optimizer works under the COMMONJS environment, such as R.js https://github.com/jrburke/r.js/.

       Define ("MyModule",  //define a module            [' foo ', ' bar '], function            (foo, bar) {///module definition function, dependent on Foo  bar as a parameter to map to function
                Here to create your module                var mymodule = {                    dostuff:function () {                        console.log (' Yay, stuff ');                    }                };                return mymodule;            }       );
       The second way of defining       define (' MyModule ', [' Math ', ' graph '], function (math, graph) {            return {                plot:function (x, y) { C13/>return Graph.drawpie (Math.randomgrid (x, y));}}       );

Require often uses code that loads top-level JavaScript files or modules.

Foo Bar is a two external module. Two modules are loaded after the output is passed as the callback function in the Require ([' foo ', ' bar '], function (foo, bar) {    //    foo.dosomething ()})

Dynamic load Dependency

Define (function (require) {    var isReady = false, Foobar;    Require ([' foo ', ' bar '], function (foo, bar) {        IsReady = true;        Foobar = foo () + bar ();    });    return {        isready:isready,        Foobar:foobar    }})


Learn about AMD: Plugins

Use AMD to load free-form content//In such a way that it can be used for template dependencies in order to work on skinning when the page is loaded define (['./templates ', ' text!. /template.md ', ' css!. /template.css '], function (templates, template) {    console.log (templates);});


Although the demo sample above includes the CSS. Used to load CSS dependencies. But there are some caveats to this approach. Party CSS is completely loaded. It does not necessarily take effect entirely. Depends on how the creation process is handled. It may also be included in the optimized file using CSS as a dependent file, so. Be cautious when using CSS as a loading dependency.



The demo sample can be viewed simply as Requirejs ([' app/mymodule '), function () {}). Indicates that the top-level global object of the loader is being used.

Here's how to load the top-level module Nahor using a different AMD loader, using the Define () function, assuming that the tower accepts a local module parameter. The demo sample for all require ([]) applies to both types of curl.js and Requirejs.



Modular JavaScript design mode (i)

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.