[英]How do I add “onload” to my Dojo class?
我想在我的自定義Dojo類中添加一個“onload”函數,以便它可以調用注冊事件的函數 - 類似於myWidget.addOnLoad(...)
我的類不是Dijit,它是一個使用dojo.declare的簡單類。 創建后,會調用幾個函數(xhr等)來初始化類,我需要能夠通知其他javascript函數,即小部件已加載並准備就緒。
您是否考慮過使用dojo.publish()在窗口小部件准備好后發布主題? 或者,如果其他代碼具有對窗口小部件的引用,則可以在加載窗口小部件時調用窗口小部件實例上的空函數(稱為“已加載”),然后引用該實例的其他代碼可以執行dojo .connect到該窗口小部件實例的“已加載”方法,以便在調用該方法時收到通知。
正如jburke已經指出的那樣 Dojo讓你很容易:dojo.connect就是你所需要的。 這是一個例子:
a = {
loaded: function() { console.log('[a] loaded'); }
}
b = {
dependentAction: function() { console.log('[b] dependentAction'); }
}
dojo.connect( a, 'loaded', b, 'dependentAction' );
a.loaded()
// prints:
// [a] loaded
// [b] dependentAction
然后就是執行a.loaded()
你和加載完成后a
。
所以我繼續並基本上復制了Dojo addOnLoad函數並將其添加到我的類中。 它似乎工作。 我看了做pub / sub或dojo.connect,但我覺得這是最干凈,最容易識別的解決方案。
下面是了解它的必要內容,再次從dojo.js中刪除並插入我的類:
_onto : function(arr, obj, fn){
if(!fn){
arr.push(obj);
}else if(fn){
var func = (typeof fn == "string") ? obj[fn] : fn;
arr.push(function(){ func.call(obj); });
}
},
_loaded : function() {
this._loadNotifying = true;
this._postLoad = true;
var mll = this._loaders;
for(var x = 0; x < mll.length; x++){
try{
mll[x]();
}catch(e){
throw e;
console.error("addOnLoad callback failed: " + e, e); /* let other load events fire, like the parser, but report the error */
}
}
this._loadNotifying = false;
//Make sure nothing else got added to the onload queue
//after this first run. If something did, and we are not waiting for any
//more inflight resources, run again.
if(this._postLoad && this._inFlightCount == 0 && mll.length){
this._loaded();
}
},
addOnLoad : function(/*Object?*/obj, /*String|Function?*/functionName){
this._onto(this._loaders, obj, functionName);
if(this._postLoad && !this._loadNotifying){
this._loaded();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.