代码之家  ›  专栏  ›  技术社区  ›  olore

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

  •  1
  • olore  · 技术社区  · 17 年前

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

    3 回复  |  直到 17 年前
        1
  •  3
  •   jrburke    17 年前

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

        2
  •  1
  •   Community Mohan Dere    9 年前

    作为 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 .

        3
  •  0
  •   olore    17 年前

    所以我继续前进;基本上复制了Dojo addOnLoad函数&把它添加到我的课堂上。它似乎正在发挥作用。我考虑过做一个酒吧/酒吧或dojo.connect,但我觉得这是最干净、最容易识别的解决方案。

    _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();
        }
    }