AMD Brief Introduction
AMD is the abbreviation of asynchronous module Definition, that is, asynchronous modules loading mechanism. The specification is an API specification of asynchronous dynamically loaded JavaScript code, proposed by COMMONJS. AMD is a simple and elegant way to get a lot of mainstream JavaScript framework in favor of the mainstream JavaScript open source framework gradually began to use AMD specifications to implement the dynamic loading of its code modules. With the growing popularity of AMD, JavaScript framework migration becomes more convenient during the development process, and it is also easy to introduce multiple JavaScript frameworks with different advantages and features in an application.
Working principle of AMD
AMD's API specification is very concise and contains only one function called define:
define ([Module-name?], [Array-of-dependencies], [Module-factory-or-object]);
which
Module-name: module identification, can be omitted.
Array-of-dependencies: Depends on the module that can be omitted.
Module-factory-or-object: A specific implementation of the module, or a JavaScript object.
The first parameter, Module-name, refers to the module name identification, which does not have a practical effect in AMD loading and is only identified as a name. If the first argument is omitted, then the module becomes an anonymous module.
The biggest advantage of the anonymous module is that it can reduce the coupling of the code itself and the owning module. This class of modules conforms to the DRY (Don ' t repeat yourself) principle that the module files can be placed in any location without the need to modify the contents of the file itself. As a familiar Java class, its class name and package name must conform to a certain format, file names and class names need to be consistent, and files must be placed under the appropriate package path. In the case of AMD-loaded dojo, if a module is an anonymous module, then the module's filename is the module identifier.
The advantages of AMD
Advantages of anonymous Modules
Here's a comparison of traditional module loading and AMD methods to see what the advantages of anonymous modules are:
In earlier versions of Dojo, a dog class was created that inherits from the animal class. The file structure is shown in the following illustration:
Figure 1
The following declarations are made in the base class animal:
Listing 1
Dojo.provide ("Animal"); Used to initialize the JS file and make it a dojo module |
In non-AMD situations, the file name and provide must be consistent (that is, the file name is consistent with the right portion of the last decimal point of the module ID), otherwise dojo.require cannot initialize the module correctly.
At this point, continue to introduce subclasses, such as the Cat class, Tiger class, to differentiate between the base class and the like, move the animal base class to a separate folder, as shown in the following figure:
Figure 2