我想在我的自定义 Dojo 类中添加一个“onload”函数,以便它可以调用为事件注册的函数——比如 myWidget.addOnLoad(...)
我的课程不是 Dijit,它是一个使用 dojo.declare 的简单课程。创建后,调用几个函数(xhr 等)来初始化类,我需要能够通知其他 javascript 函数小部件已加载并准备就绪。
我想在我的自定义 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();
}
}