1、在正式进入dojo事件之前,先看一下如何使用dojoConfig配置dojo的行为。
有两种方式配置,第一种方式使用dojoConfig:
<!-- set Dojo configuration,load Dojo --> <script> dojoConfig= { has: { "dojo-firebug": true },parSEOnLoad: false,foo: "bar",async: true }; </script> <script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"></script>第二种方式,使用data-dojo-config属性:
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js" data-dojo-config="has:{'dojo-firebug': true},foo: 'bar',async: 1"> </script>两种方式是等价的。
2、DOM事件
Dojo改进了Dom事件处理,通过处理浏览器差异,防止内存泄露等。dojo通过调用dojo/on处理DOM事件。
@H_404_17@
require(["dojo/on","dojo/dom","dojo/dom-style","dojo/mouse","dojo/domready!"],function(on,dom,domStyle,mouse) { var myButton = dom.byId("myButton"),myDiv = dom.byId("myDiv"); on(myButton,"click",function(evt){ domStyle.set(myDiv,"backgroundColor","blue"); }); on(myDiv,mouse.enter,"red"); }); on(myDiv,mouse.leave,""); }); });
Note:默认情况下,dojo/on会以传入的节点(第一个参数)作为上下文环境执行事件处理方法。当需要进行事件委托时,上面的方法需要稍作改动,我们可以使用dojo/_base/lang.hitch来指定事件处理方法执行的上下文环境。
copedButton1 = dom.byId("myScopedButton1"),myScopedButton2 = dom.byId("myScopedButton2"),myObject = {
id:"myObject",onClick:function(evt){
alert("The scope of this handler is " + this.id);
}
};
// This will alert "myScopedButton1"
on(myScopedButton1,myObject.onClick);
// This will alert "myObject" rather than "myScopedButton2"
on(myScopedButton2,lang.hitch(myObject,"onClick"));
});
@H_404_17@3、NodeList事件
<button id="button1" class="clickMe">Click me</button> <button id="button2" class="clickMeAlso">Click me also</button> <button id="button3" class="clickMe">Click me too</button> <button id="button4" class="clickMeAlso">Please click me</button> <script> require(["dojo/query",function(query,lang) { var myObject = { id: "myObject",onClick: function(evt){ alert("The scope of this handler is " + this.id); } }; query(".clickMe").on("click",myObject.onClick); query(".clickMeAlso").on("click","onClick")); }); </script>Note:dojo/query返回的结果就是NodeList对象。NodeList是一个JavaScript数组,不过它提供了很多有用的方法来操作数组中的每一个元素。
4、事件发布/订阅
//event.js define(["dojo/on","dojo/topic","dojo/domready"],topic){ return { publish:function(id){ var node = dom.byId(id); on(node,function(){ topic.publish("alertuser","i am alerting you"); }); } }; }); //index.html <button id="alertButton">Alert the user</button> <button id="createalert">Create another alert button</button> <script src="dojo-release-1.9.1/dojo/dojo.js" data-dojo-config="async:true"></script> <script> require(["custom/event","dojo/topic"],function(event,topic){ event.publish("alertButton"); topic.subscribe("alertuser",function(text){ alert(text); }); }); </script>Note:通过dojo/on监听的事件或者通过topic.subscribe订阅的事件都有相应的方法取消。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。