dojo 二 AMD模块

时间:2023-03-10 04:24:10
dojo  二 AMD模块

可参考官方教程:http://dojotoolkit.org/documentation/tutorials/1.7/hello_dojo/
教程里主要定义了两个方法,setText设置文本内容和restoreText重置文本内容。
这两个方法通过dojo.define这个方法来定义。

// In
demo/myModule.js (which means this code defines
// the
"demo/myModule" module):
define([
    // The dojo/dom module is required by this
module, so it goes
    // in this list of
dependencies.
    "dojo/dom"
],
function(dom){
    // Once all modules in the dependency list
have loaded, this
    // function is called to define the
demo/myModule module.
    //
    // The dojo/dom module is passed as the
first argument to this
    // function; additional modules in the
dependency list would be
    // passed in as subsequent
arguments.
    var oldText =
{};
    // This returned object becomes the defined
value of this module
    return {
        setText:
function(id, text){
            var node =
dom.byId(id);
            oldText[id] =
node.innerHTML;
            node.innerHTML =
text;
        },
        restoreText:
function(id){
            var node =
dom.byId(id);
            node.innerHTML =
oldText[id];
            delete
oldText[id];
        }
    };
});
define 方法引用了必要的类,就像java 中的
import;并且还包含了对业务逻辑的实现,
并通过return来返回,以上就是myModule.js文件的全部内容。
那么在html页面里,通过dojo.require来加载上面的js代码,
//
Require the module we just created
require(["demo/myModule"],
function(myModule){
    // Use our module to change the text in the
greeting
    myModule.setText("greeting",
"Hello Dojo!");
    // After a few seconds, restore the text to
its original state
    setTimeout(function(){
        myModule.restoreText("greeting");
    }, 3000);
});
上面的代码通常放在<body>内执行。
demo/myModule指的
demo/myModule.js,有关路径问题参看这里:Dojo 学习(0):
require的路径问题

加载成功后就可以通过 myModule.setText
这样的方式来调用了。
在这里暂且先总结为:dojo.define 方法仅用于定义和声明,dojo.require 方法仅用于异步加载js文件