官网教程:Events with Dojo
在元素上绑定events,需要引用包dojo/on,通过on方法来实现。
<
button
id
=
"myButton"
>Click me!</
button
>
<
div
id
=
"myDiv"
>Hover over me!</
div
>
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,
function
(evt){
domStyle.set(myDiv,
"backgroundColor"
,
"red"
);
});
var handler =
on(myDiv, mouse.leave,
function
(evt){
domStyle.set(myDiv,
"backgroundColor"
,
""
);
});
handler.remove();//移除event
on.once(
myDiv,
mouse.leave,
function
(evt){
domStyle.set(myDiv,
"backgroundColor"
,
""
);
});
});
on方法不需要前缀。包括三个参数。
第一个:需要绑定events的元素
第二个:event名称
第三个:处理event的方法体,这个方法体有只一个参数,为event的对象,包括一些属性和方法,如果需要传递其他参数,将在后面讲到。
方法on的返回值是一个简单的对象,只有一个remove方法,执行这个方法,元素就会移除这个event。
还有一个方法on.once(element,event
name,handler),参数同on一样,这个方法顾名思义就是只执行一次,在执行了handler后将会自动remove。
一个元素可以绑定多个events,每个event按照绑定的
先后顺序来
执行的。
----------------------------------
require([
"dojo/on"
,
"dojo/dom"
,
"dojo/_base/lang"
,
"dojo/domReady!"
],
function
(on, dom, lang) {
var
myScopedButton1 =
dom.byId(
"myScopedButton1"
),
myScopedButton2 =
dom.byId(
"myScopedButton2"
),
myObject = {
id:
"myObject"
,
onClick:
function
(arg){
alert(
"The scope of
this handler is "
+ this.id + " , value = " +
arg
);
}
};
// This will alert
"myScopedButton1"
on(myScopedButton1,
"click"
, myObject.onClick);
// This will alert "myObject" rather than
"myScopedButton2"
on(myScopedButton2,
"click"
, lang.hitch(myObject,
"onClick",
"something"
));
});
handler可以是一个方法体,也可以是一个对象里定义的方法,这个方法可以带多个参数。
如果handler表示为object.method,那么无法传递参数,而method中的this指代的是当前的元素。
如果handler用方法lang.hitch(object,method
name,[arg1,[arg2,.....]])来表示,则可能传递N个参数,但method中的this指代的是object。
define(["dojo/aspect"], function(aspect){ aspect.after(dojo, "xhr", function(deferred){ // this is called after any dojo.xhr call }); // this will execute the original dojo.xhr method and then our advising function dojo.xhr("GET", {...}); });
define(["dojo/aspect"], function(aspect){ aspect.before(dojo, "xhr", function(method, args){ // this is called before any dojo.xhr call if(method == "PUT"){ // if the method is PUT, change it to a POST and put the method in the parameter string args.url += "?x-method=PUT"; // return the new args return ["POST", args]; } }); // this will execute the original our advising function and then dojo.xhr dojo.xhr("PUT", {...}); });
define(["dojo/aspect"], function(aspect){ aspect.around(dojo, "xhr", function(originalXhr){ return function(method, args){ // doing something before the original call var deferred = originalXhr(method, args); // doing something after the original call return deferred; } }); dojo.xhr("PUT", {...}); });
来源:https://www.cnblogs.com/tiandi/p/3415903.html