AMD advanced Applications (translation)

Source: Internet
Author: User
Tags configuration settings define function

Dojo now supports modules written in the asynchronous Module Definition (AMD) format, which makes code easier to author an D Debug. In this tutorial, we learn all on this new module format, and explore how to write an application using it.

Dojo now supports asynchronous schema-defined modules, which can make your code more readable and debug. In this chapter, we'll learn about the pattern and learn how to use it in your app.

This tutorial are a follow-up to the Introduction to AMD, so make sure you understand the basics of AMD first.

This chapter is a continuation of introduction to AMD, so please make sure you understand some of the basics of AMD.

Throughout this tutorial, we'll be is referring to a hypothetical application with a filesystem structure the so looks like T His

Through this article, we will be virtual an application whose file structure looks like this:

1 /2    index.html3     js/4         lib/5             dojo/6              dijit/7             dojox/8         my/9         util/

As can see, this structure are different from what we discussed in the previous tutorial, so we'll explain how to con Figure the loader-make-this-work. But first let's revisit and require with define a few more details ...

As you can see, this structure is not the same as the file structure in the example above. So we'll show you how to configure the loader to keep the code running. But before we do, we'll review the require and define functions in a few examples.

Delving deeper into requireMore in-depth understanding of the Require function

The require function accepts the following parameters:

The Require function accepts the following parameters.

    1. configuration (optional, default=undefined): An object with loader configuration Options-this allows Reconfigure the loader at run-time.

      Configuration: (optional, default =undefined): Loader configuration Settings Object-This object allows you to reconfigure the loader at run time.

    2. dependencies (optional, default=[]): An array of module identifiers. If specified, these modules would be resolved before your code is evaluated. They is loaded in the order they is listed and passed as parameters to your callback function, also in order.

      Dependent (optional, default =[]): module identity Array. If specified, these modules will be loaded before your code is executed. The modules are loaded in their order and passed to the callback function sequentially as parameters.

    3. callback : A function containing the code want to run, depends on the modules in Depe Ndencies . You need to wrap your code in a callback function in order to support asynchronous loading and to is able to use Non-globa L references to the modules.

callback function: The function is the code you want to run based on the module loaded in the dependent parameter. In order to support asynchronous loading and be able to use a non-globally named module, you must package your code in a callback function.

The configuration parameter can simply is omitted and no empty placeholder value is necessary.

The configuration parameters can be omitted, and no empty placeholders are required.

We ' ll cover configuring the loader in more detail below; For now here's an example of using the configuration parameter of require :

We'll cover the loader configuration in more detail below. Here is an example of using configuration parameters in the Require function.

1 require ({2     baseUrl: "/js/",3    packages: [4         { Name: "Dojo", Location: "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/" },5         {name: "My", Location: "My" }6    ]7 }, ["My/app"]);

Here, we've changed the configuration slightly to point the package to the dojo Google CDN. Cross-domain loading support was implicit in the AMD format.

Here, we changed some of the dojo package configuration and pointed the package to Google Cdn. The AMD mode is supported across domains by default.

Note that the all configuration options can is set at runtime. In particular, async , tlmSiblingOfDojo , and pre-existing has tests cannot are changed once the loader is loaded. Additionally, most of the configuration data is shallow copied, which means, the couldn ' t use this mechanism to, for example, Add more keys to a custom configuration Object-the object would is overwritten.

It is important to note that all configurations can be set at run time. However, async thetlmSiblingOfDojo以及预先存在的has等模块,一旦通过加载器加载后,就不能再修改了。此外,大多数的配置数据都是浅拷贝,这意味着一个配置对象可能会有多个指针引用着该对象,该对象中的数据随时都与可能被覆写。

Delving deeper into define 深入了解define函数

The define function accepts the following parameters:

The Define function contains the following parameters:

    1. ModuleID (optional, default=undefined): a module identifier. This parameter was largely a historical artifact of early AMD loaders or to support PRE-AMD Dojo, and should not being pro vided.

      Module ID (optional parameter, default value =undefined): a module ID. This parameter is basically created to be compatible with the previous AMD mode two, which we do not need to provide.

    2. Dependencies (optional, default=[]): An array of module identifiers that is dependencies of your module. If specified, these modules'll be resolved before your module is evaluated and they would be passed as parameters to your Factory function, in order.
      Dependency (optional parameter, default value =[]): The module identity collection that your module needs to reference. These dependent modules will be loaded and passed to the factory function in the order of the dependent modules before the main code of your module is executed.
    3. Factory: The value of your module, or a "factory" function that would return the value

Factory: The function is the body of the module you define, or the factory function returns the caller as the return value.

It ' s important to remember if defining a module, the factory function is only ever invoked once -the return Ed value is cached by the loader. On a practical level, this means then modules can very easily share objects (similar to static properties in Othe R languages) by loading the same module.

It is important to note that when a module is defined, the factory function is only called once-the return value is cached by the loader. This means that you can share module objects (similar to the static properties of China in other development languages) by loading the same modules.

When defining a module, the value can given as a plain object:

When defining a model, we can scope an ordinary object.

1 // In "My/nls/common.js" 2 define ({3     Greeting: "Hello!" , 4     Howareyou: "How is it?" 5 });

Keep in mind so if you do define a module without using a factory function, you won ' t is able to reference any Dependenc IES, so the type of definition is rare and usually only gets used by i18n bundles or simple configuration objects.

Keep in mind that if you use the Factory mode to define the module, you cannot access any dependencies that are referenced. Therefore, this type of definition is not commonly used, only when the multi-language support is simple to configure the object when used.

How does the loader work?

When you call require to load some modules, the loader have to find the code for the module and then pass it as a parameter T O Your callback function so can use it.

When you call the Require function to load some modules, the loader will first find the code that you called the module, and then pass the module corresponding parameters to the callback function.

    1. First the loader have to resolve The module identifier you passed. This involves putting together the baseUrl with the module identifier itself, plus taking to account any MO Difications required by other configuration options, such as map (discussed later in more detail).

      First, the loader resolves the identity of the module that you loaded. The BaseURL of the configuration is combined with the identity of the module itself when parsing, taking into account the parameters of other configuration items (such as mapping parameters).

    2. at the loader have a URL for the module and can load the actual file by creating a new Scri PT element on the page and setting the src attribute to the module ' s URL. The

      Loader already has the URL address of the module, and can add a script node to the page and assign the URL address of the module to the SRC attribute of the script node.

    3. Once The file is loaded and evaluated, its result is set as the value of the module.

      Once the file is loaded, the results contained in the file are set to the value of the module.

    4. The loader maintains a reference to each module, and the next time the module is requested the loader would r Eturn the existing reference.

The loader contains a reference to each module, so the next step, the module loaded by the loader returns its own reference.

When an AMD module was loaded, the code is inserted to a new script element on the page which results in the define functio n being called. The same process as above happens to load a dependencies passed define to and then the loader's reference to your module is Set to the value returned by the factory function you passed to define . (If you passed a value, rather than a function define to and then the loader's reference to your module is set to that value.)

When an AMD module is loaded, a new script node is added on the page where the define function is called.

Configuring the Loader configuration Loader

For legacy compatibility reasons, Dojo's loader runs by default in synchronous mode. To put the ' A ' in ' AMD ', we need to explicitly configure the loader to run asynchronously. This is the setting of the async configuration to true :

For reasons of compatibility with older versions, dojo runs in synchronous mode by default. But the meaning of a in AMD means that contemporary DOJOAMD patterns are run asynchronously. In the configuration, async set the property to True.

1 <script data-dojo-config= "async:true" src= "Js/lib/dojo/dojo.js" ></script>

You should get on the habit of enabling this as a standard practice-only disable it when you know you need synchronous b Ehavior. The next thing we need to do be configure the loader with information on where our modules is located:

You should use this configuration as a habit unless you explicitly know that you want to perform an action synchronously. The next thing to do is to configure the local model path-related information.

1 varDojoconfig = {2BASEURL: "/js/",3Tlmsiblingofdojo:false,4 Packages: [5{Name: "Dojo", Location: "Lib/dojo" },6{Name: "Dijit", Location: "Lib/dijit" },7{Name: "Dojox", Location: "Lib/dojox" },8{Name: "My", Location: "My", Main: "App" }9     ]Ten};

Keep in mind you must set the dojoConfig variable before loading dojo.js . Read the Configuring Dojo tutorial if you haven ' t already.

Note that you are required to set dojoconfig after loading dojo.js.

Let's examine the configuration options we ' re using:

Let's look at the options we configured:

baseUrl(default = The path of the folder Dojo.js is loadedfrom): Defines the base URL for loading packages. For example, if you try to load the module "My/widget/person", the loader would try to load it from:

BASEURL (the default is the directory where the loaded dojo.js resides): Defines the underlying path to the load package. For example, if you want to load the "My/widget/person" module, the loader will load from the path below.

1 /js/my/widget/person.js

This allows us to place our files wherever are most convenient in the filesystem (in this case, the "JS" folder) and still Use only the relevant parts of the path in module ids-we don ' t need require(["js/my/widget/Person"]) to, we can simply require(["my/widget/Person"]) because we have config Ured the loader to use "/js/" as a base-to-prepend to all-module IDs when actually loading the source file.

This allows us to put our defined files in the appropriate physical file directory, but only to refer to part of the path as the ID identifier of the module. We don't need to require(["js/my/widget/Person"]) , simply use require(["my/widget/Person"]) it, because we've configured the BaseURL property to "/js/" in the loader, and when the module is loaded, all the module paths get the module source file in the same way that the baseurl+ module identifies it.

tlmSiblingOfDojo(default = true): By default, the loader expects to find modules in folders that is siblings of the folder The L Oader was loaded from (remember, with Dojo the loader are loaded when your script element loads dojo.js ). If your file structure is like this:

tlmSiblingOfDojo:默认情况下,加载器可以查找兄弟目录下的所有模块,并加载,例如:

1 /2     js/3         dojo/4         dijit/5         dojox/6         my/ 7         util/

Then you don ' t need to configure baseUrl or tlmSiblingOfDojo -your top-level modules is siblings of the folder dojo.js WA s loaded from, so is tlmSiblingOfDojo true.

In this case, you don't need to configure BaseURL and properties anymore tlmSiblingOfDojo . Because your custom model top-level directories and dojo.js are in the same directory as the sibling directory, and the model case, tlmSiblingOfDojo the value is true.

packages: An array of the package configuration objects. At the very fundamental level, packages is simply collections of modules. dojo, dijit and is all dojox examples of packages. Unlike a simple collection of modules in a directory, however, packages is imbued with some extra features that Significa ntly Enhance module portability and ease-of-use. A Portable package was self-contained and also can be installed through tools like CPM. A package configuration allows specify:

Package: is a set of package configurations. At its most basic level, a package is a collection of groups of modules, such as Dojo, Dijit, Dojox, and so on. Rather than simply placing the module in a single directory, the package contains additional features that can improve portability and ease of use of the package. Packages are self-contained and can be installed through tools such as CPM, and the configuration information for a package is as follows:

  • name: The name of the package. This should match the name of the folder that contains the modules.

    Name: The names of the packages. The name should match the name of the directory where the package resides.

  • location : The "The location of the" package; can either is a path relative to baseUrl or an AB Solute path. We would like to being able to load modules from the Dojo package as "Dojo/dom" rather than "lib/dojo/dom" (Take another look At the file structure at the beginning of this tutorial), so we specify the location property of the Dojo PA Ckage to IS "Lib/dojo". This informs the loader a attempt to load the "dojo/dom" module should load the file "/js/lib/dojo/dom.js" (Remember , because of baseUrl "JS" would be prepended).

    Location: The location of the package, which can be either a relative path based on BaseURL or an absolute path. We want to be able to load modules from dojo packages in such a way dojo/dom, rather than through Lib/dojo/dom. So, we developed the package path for Lib/dojo. By this mode, when you load the Dojo/dom module, the/js/lib/dojo/dom.js file is actually loaded.

  • Main (optional, default = main.js): Used to discover the correct module to load if someone tries to require the PACKAG E itself. For example, if you were-to-try to require "dojo", the actual file, the would was loaded is "/js/dojo/main.js". Since we ' ve overridden the "my" package, if someone required "my", they would actually load "/js/my/app. JS ".

Main (optional parameter, default value =main.js): If someone requests the package itself, it points to a default module file. For example, if we request dojo, the actual file that the request points to may be/js/dojo/main.js. For example, we re-add the main property of my package to the app, so loading is a "/js/my/app.js" file.

    • If we tried to require "util", which are not a defined package, the loader would try to load "/js/util.js". You should always define all of your packages in the loader configuration.

      If we request util, the module is an undefined module, the loader will attempt to load the/js/util.js file, so you must define all the packages you need in the loader configuration.

Using portable modules with lightweight modules

One of the most important features of the new AMD loader are the ability to create fully portable packages. For instance, if you had a application that needed to use modules from the different versions of Dojo, the new loader MAK Es this very easy.

Suppose you has an application built on a older version of Dojo and you want to update to the latest and greatest 1.10 r Elease, but there is some updates to Dojo that render your older code non-functional. You can still update to the current release of dojo for new code, while using a legacy release of dojo for you older code. This can is accomplished with the map configuration property:

One of the most important features of the new AMD Downloader is the ability to create completely lightweight module packages. For example, if you have an application that has to use different versions of a module from dojo, the new loader can easily solve this problem.

Suppose you now have an application based on the old version of Dojo, and now you want to upgrade to the latest version, which is version 1.10. However, there may be some updates that will invalidate your previous code. You can still update your new volume code to the latest dojo release package, and use the previous version of dojo for your old code. This is done through the mapping configuration.

1Dojoconfig = {2 Packages: [3{Name: "Dojo16", Location: "Lib/dojo16" },4{Name: "Dijit16", Location: "Lib/dijit16" },5{Name: "dojox16", Location: "lib/dojox16" },6{Name: "Dojo", Location: "Lib/dojo" },7{Name: "Dijit", Location: "Lib/dijit" },8{Name: "Dojox", Location: "Lib/dojox" },9{Name: "Myoldapp", Location: "Myoldapp" },Ten{Name: "My", Location: "My" } One     ], A Map: { - Myoldapp: { -Dojo: "Dojo16", theDijit: "Dijit16", -Dojox: "dojox16" -         } -     } +};

AMD advanced Applications (translation)

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.