如何在我的Dojo类中添加“onload”?

时间:2009-07-13 12:32:30

标签: javascript dojo widget onload

我想在我的自定义Dojo类中添加一个“onload”函数,以便它可以调用注册事件的函数 - 类似于myWidget.addOnLoad(...)

我的班级不是Dijit,它是一个使用dojo.declare的简单类。在创建时,调用几个函数(xhr等)来初始化类,并且我需要能够通知其他javascript函数小部件被加载和放大。准备好了。

3 个答案:

答案 0 :(得分:3)

您是否考虑过使用dojo.publish()在窗口小部件准备好后发布主题?或者,如果其他代码具有对窗口小部件的引用,则可以在加载窗口小部件时调用窗口小部件实例上的空函数(称为“已加载”),然后引用该实例的其他代码可以执行dojo .connect到该窗口小部件实例的“已加载”方法,以便在调用该方法时收到通知。

答案 1 :(得分:1)

作为jburke already pointed out 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

答案 2 :(得分:0)

所以我继续前进基本上复制了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();
    }
}