Dojo learning-0: Introduction to AMD Modules

Source: Internet
Author: User
Tags define function

Dojo learning-0: Introduction to AMD Modules
Original article: http://dojotoolkit.org/documentation/tutorials/1.10/modules/
Difficulty level: elementary Dojo version: 1.10

If you are migrating from a version of Dojo lower than 1.7, you may find the1.8 versionof this tutorial useful as it provides some guidance on migrating from Dojo's old module system to AMD. this tutorial will focus strictly on AMD.

Overview

Since Dojo 1.7, Dojo uses the asynchronous module definition (AMD) format to define modules. It is much more powerful than traditional methods, including full asynchronous operations, true package portability, better dependency management, and enhanced error debugging. It is a community-driven specification. modules written in AMD format can be used in any AMD-compatible loader or library. This article will elaborate on AMD and explain how to use it.

What is module?

A module is simply a value that can be referenced. If your module needs to expose some data or methods, the data or methods must represent the attributes of an object in this module. In actual development, we generally do not create a module to encapsulate a simple variable, such as var tinyModule = 'simple value'. Of course you need to do the same. The main value of Modules is to modularize your code and split different functions into different logical units. For example, if you want to define a person with a name address and some other methods, you 'd better encapsulate it together. A module corresponds to a file in the file system.

How can I create a module?

In AMD, to create a module, you must register it in loader.

What is loader? Loader is a piece of JavaScript code used to process module definition and loading. After you load dojo. js or require. js, you have a loader. Interaction with loader:RequireAndDefine..

The global method define allows you to register a module in loader. Let's look at a simple example:

 
 
  1. define(5);
Very simple, but it works well-now we have defined a module with a value of 5.
 
 
  1. define({
  2. library: 'dojo',
  3. version: 1.10
  4. });
The above example goes further. When the module is loaded, we get an object that contains two attributes.

 
 
  1. define(function(){
  2. var privateValue = 0;
  3. return {
  4. increment: function(){
  5. privateValue++;
  6. },

  7. decrement: function(){
  8. privateValue--;
  9. },

  10. getValue: function(){
  11. return privateValue;
  12. }
  13. };
  14. });

In the above example, we pass a function into define. This function is executed, and its return value is saved as a module by loader. This Code uses the closure to create a private variable privateValue, which cannot be directly accessed by external code, but can be accessed by Returning Methods of the object, the returned object will be the value of the module (modules's value ).


How to load a module?

Beginners need to know how to mark modules. To load a module, you must first identify it. Similar to the module/package in other languages, an AMD module consists of its path and file name. Now we save the preceding sample code as the following file:

 
 
  1. app/counter.js

Let's add a loader (Dojo) and index.html (entry point of the application ). The overall file structure is as follows:
 
 
  1. /
  2. index.html
  3. /dojo/
  4. /app/
  5. counter.js

The index page is as follows:
 
 
  1. <body>
  2. <script src="dojo/dojo.js" data-dojo-config="async: true"></script>
  3. <script>
  4. require([
  5. "app/counter"
  6. ], function(counter){
  7. log(counter.getValue());
  8. counter.increment();
  9. log(counter.getValue());
  10. counter.decrement();
  11. log(counter.getValue());
  12. });
  13. </script>
  14. </body>

Let's analyze the following content:

  1. App/counter. js module definition file. After calling this file, a module will be registered in loader. Note that the module we define here is a reference pointing to an object, rather than a constructor-this also means that no matter how many times the module is loaded, what we get is a reference pointing to the same object. In general, the module returns constructor, but in some cases, it is more appropriate to return a single-piece object.
  2. In the file system, the rule for locating the module is to search the subdirectory of the directory where index.html is located, and this subdirectory must be the same as the AMD loader directory (dojo/dojo. js), through this rule we do not need to perform any configuration, loader can know that the module id "app/counter" is pointing to app/counter. js file, load it, and register the returned value as a module.
  3. In the index.html file, we call require to load the "app/counter" module. We can also use the simplest module Loading Method require (["app/counter"]). This method is applicable to scenarios that do not require a module return value (module reference), but only take advantage of its side effects (such as expanding other modules ). If you need a module return value (module reference), you must provide a callback function. After the module is correctly loaded, loader passes the module as a parameter to the callback function and calls it. Like other functions, the parameter name can be any-the parameter name is not necessarily the same as the module name. Of course, as a best practice, it is recommended that the parameter name be the same as the module name.


Module for Loading Modules-Modules Loading Modules

The previous example is very simple and only shows the basic usage of the define function. When our applications are composed of a bunch of well-organized modules, there must be dependencies between modules. The define function can automatically load dependencies. The list of dependent modules must be passed to the define function.


 
 
  1. define([
  2. "dojo/_base/declare",
  3. "dojo/dom",
  4. "app/dateFormatter"
  5. ], function(declare, dom, dateFormatter){
  6. return declare(null, {
  7. showDate: function(id, date){
  8. dom.byId(id).innerHTML = dateFormatter.format(date);
  9. }
  10. });
  11. });

This example shows more features of AMD applications:

  1. Multiple dependencies-the dependency LIST parameters include "dojo/dom" and an imaginary "app/dateFormatter" module.
  2. Returns a constructor. Here we give the module a proper name, such as "app/DateManager ". When other code uses this module, the Code is as follows:

  
  
  1. require([
  2. "app/DateManager"
  3. ], function(DateManager){
  4. var dm = new DateManager();
  5. dm.showDate('dateElementId', new Date());
  6. });

To develop a Dojo application, AMD is the first theme you need to be familiar with, and declare is the second crucial function. If you are not familiar with dojo/_ base/declare, click here to learn: tutorial!

Use plugins

In addition to the conventional modules, AMD loader also divides a class of modules based on functional features, called plugin. Plugins is used to expand the loader feature, rather than simply loading AMD modules. Plugins are similar to common modules to some extent, but behind the module identifier is "! ", Used to identify this as a plugin. "! "The subsequent data will be directly transferred to plugin for processing. Some examples may be helpful for understanding. Dojo provides several default plugins. Four of the most important ones are dojo/text, dojo/i18n, dojo/has, and dojo/domReady. Let's explain it one by one.

Dojo/text

Dojo/text is used to load strings (such as HTML templates) from files ). The load value is buffered. Next time, if a request for the same file exists, no network request is initiated. Builder performs inline processing on strings loaded using dojo/text. For example, to load a template for a templated widget, you can define the module as follows:


 
 
  1. // in "my/widget/NavBar.js"
  2. define([
  3. "dojo/_base/declare",
  4. "dijit/_WidgetBase",
  5. "dijit/_TemplatedMixin",
  6. "dojo/text!./templates/NavBar.html"
  7. ], function(declare, _WidgetBase, _TemplatedMixin, template){
  8. return declare([_WidgetBase, _TemplatedMixin], {
  9. // template contains the content of the file "my/widget/templates/NavBar.html"
  10. templateString: template
  11. });
  12. });

Dojo/i18n

Dojo/i18n loads the relevant language resource package according to the locale definition of the browser. The usage is as follows:

 
 
  1. // in "my/widget/Dialog.js"
  2. define([
  3. "dojo/_base/declare",
  4. "dijit/Dialog",
  5. "dojo/i18n!./nls/common"
  6. ], function(declare, Dialog, i18n){
  7. return declare(Dialog, {
  8. title: i18n.dialogTitle
  9. });
  10. });


For more information about i18n, see internationalization tutorial. Dojo/has

The Dojo's loader contains an implementation of the has. js Feature Detection API. the dojo/hasplugin can be used to dynamically adjust the dependency module. The usage is roughly as follows:


 
 
  1. // In "my/events. js"
  2. Define ([
  3. "Dojo/dom ",
  4. "Dojo/has! Dom-addeventlistener ?. /Events/w3c:./events/ie"
  5. ], Function (dom, events ){
  6. // If the value of "dom-addeventlistener" is true, the event is "my/events/w3c"
  7. // Otherwise, the event is "my/events/ie"
  8. Events. addEvent (dom. byId ("foo"), "click", function (){
  9. Console. log ("Foo clicked! ");
  10. });
  11. });

Dojo/domReady

Dojo/domReady is an alternative to dojo. ready. It will only block the process until the DOM is ready. The usage is as follows:


 
 
  1. // In "my/app. js"
  2. Define (["dojo/dom", "dojo/domReady! "], Function (dom ){
  3. // This function will not be executed until the DOM is ready.
  4. Dom. byId ("someElement ");
  5. });

Note that in the callback function, we do not define any corresponding parameters for dojo/domReady. This is because the return value is useless to us-we just use it to delay the execution of the callback function. For modules or plugins that do not require the returned values, place them at the end of the list of dependent modules, because the parameters in the callback function correspond to the module names in one order.

Even if you do not need to pass parameters to plugin, the exclamation point is still required. Without it, dojo/domReady will only be loaded as a dependency module, and it will not be enabled as a special function of plugin.

Summary

The basic AMD knowledge described in this tutorial will help you get started, but there will be more knowledge points later. Read the Advanced AMD Usage tutorial to learn the following:

  • If loader and packages are stored in different locations or even on different servers, how to configure loader
  • Creating packages of portable modules
  • Loading multiple versions of the same module or library
  • Load non-AMD code


Other resources
  • AMD Specification


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.