转载自:http://www.cnblogs.com/owenChen/archive/2012/12/25/2831311.html
前面两篇文章介绍了Dojo1.8的AMD以及Dojo core当中相关模块的变化。接下来我们介绍一下Dijit,Dojox这两个控件组件模块的变化。
Parser
在具体讲Dijit之前,我们先了解一下dojo/Parser模块,这个模块由原先dojo.parser转变而来。dojo对于控件的使用提供了编程式(programmatic)和声明式(declarative markup)两种方式。dojo/parser是用来翻译声明式的控件定义,并将它们渲染成控件的实例对象和控件相应的dom节点。
对于dojo/parser的调用方式如下:
require(["dojo/parser","dojo/ready"],function(parser,ready){ ready(function(){ parser.parse(); }); });
尽管在dojoConfig中依然可以写parSEOnLoad:true的配置,但是还是需要手动去require parser模块。所以代码段中的方式是推荐的方式。
在dojo/parser内部最大的变化是增强了对于符合HTML5规范的属性的支持。具体的举例如dojoType被改成data-dojo-type,对于控件属性的定义,也被统一放到data-dojo-props属性中。这种方式符合HTML5的属性定义规范。举例老的写法:
<button dojoType="dijit.form.Button" tabIndex=2 iconClass="checkmark">OK</button>
新的写法将是:
<button data-dojo-type="dijit/form/Button" tabIndex=2 data-dojo-props="iconClass: 'checkmark'">OK</button>
上面代码中的dijit/form/Button,替换了之前的dijit.form.Button,使用的是模块ID(MID),这也是我们之前在AMD的章节中讨论过的新写法。
这里需要注意的是,在使用某个MID之前,需要在require([...])调用中加载相应的模块,一般在<head>节点中,这样可以保证<body>中需要使用的控件都已经加载。
dijit widget
在1.8中,dijit包中的控件也遵循了新的模块方式的写法,即原先所有的全局的diji.*都被放到了各自相应的模块当中。如dijit.form.Button,现在为dijit/form/Button模块。
其实在dijit的这些变化当中,最先引起我注意的是dijit.byId()这个函数的变化。如今的dijit.byId()被移到了dijit/registry模块当中,相应的调用改成了registry.byId()。相应的dijit.byNode()也成了registry.byNode()。
下面我们具体介绍一下在dijit内部的一些机制和函数发生的变化,这些使我们在使用、扩展尤其是写自己的控件的时候需要注意的。
dojo/Stateful和dojo/Evented
在这里首先要引入在扩展或创建dijit时需要理解的两个比较重要的模块:dojo/Stateful和dojo/Evented。
dojo.Stateful提供了访问控件属性的统一接口:set()和get(),同时还提供了监测(watch)控件属性的能力。例如,你可以使用如下的代码:
require(["dijit/form/Button","dojo/domready!"],function(Button){ var button = new Button({ label: "A label" },"someNode"); // Sets up a watch on button.label var handle = button.watch("label",function(attr,oldValue,newValue){ console.log("button." + attr + " changed from '" + oldValue + "' to '" + newValue + "'"); }); // Gets the current label var label = button.get("label"); console.log("button's current label: " + label); // This changes the value and should call the watch button.set("label","A different label"); // This will stop watching button.label handle.unwatch(); button.set("label","Even more different"); });@H_404_75@