Dojo -- Modules篇之AMD介绍
为了使得代码更加容易维护和调试, 如何加载Dojo模块为了更好的理解Dojo的模块,在这里先写个例子,说明一下Dojo如何加载模块的。至于什么是模块以及如何创建模块,会在下面讲到。 我们先创建一个 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- load Dojo -->
<script src="./dojo/dojo.js" data-dojo-config="async: true"></script>
<script> require([ "app/counter.js" ],function (counter) { console.log(counter.getValue()); counter.increment(); console.log(counter.getValue()); counter.decrement(); console.log(counter.getValue()); }); </script>
</body>
</html>
再建立一个 define(function(){
var privateValue = 0;
return {
increment: function(){
privateValue++;
},decrement: function(){
privateValue--;
},getValue: function(){
return privateValue;
}
};
});
我们在学习其他语言的时候,例如java语言,我们可以通过包名和类名来找到这个类。这里的一个java类可以看成一个模块。那么Dojo也是可以通过文件路径和文件名来找到模块的。例如上面的app/counter.js 0 1 0 如果你想把相关的数据和操作放置在一起,那么你可以通过Dojo的module把它们组织在一起,并使用 模块引用模块当系统一复杂,必然存在模块依赖其他模块的情况。在dojo中,如何在 define([
"dojo/_base/declare","dojo/dom","app/dateFormatter"
],function(declare,dom,dateFormatter){
return declare(null,{
showDate: function(id,date){
dom.byId(id).innerHTML = dateFormatter.format(date);
}
});
});
app/dateFomatter是我们自己定义的模块,如果需要依赖 引用插件代码如下: define([
"dojo/_base/declare","dijit/_WidgetBase","dijit/_TemplatedMixin","dojo/text!./templates/NavBar.html"
],_WidgetBase,_TemplatedMixin,template){
return declare([_WidgetBase,_TemplatedMixin],{
// template contains the content of the file "my/widget/templates/NavBar.html"
templateString: template
});
});
注意,引用dojo插件时,必须加上感叹号!,如上面的代码。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |