官網教程: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", {...}); });
