简体   繁体   English

导出Javascript类函数

[英]Exporting Javascript Class Functions

I am trying to implement the module YSlow into my own project. 我正在尝试将模块YSlow实施到我自己的项目中。 A function I want to use looks like this: 我要使用的功能如下所示:

YSLOW.registerRuleset = function (ruleset) {
    YSLOW.controller.addRuleset(ruleset);
};

From what I can tell, YSlow is assigned here in the code at the beginning: 据我所知,YSlow在开头的代码中分配如下:

if (typeof YSLOW === 'undefined') {
    YSLOW = {};
}

What I want to be able to do is export this class and be able to use this function. 我想要做的是导出此类并可以使用此功能。 I would usually just put: 我通常会把:

exports.sayHello = function() {
    return "Hello"
};

However, I am unsure how to properly communicate with registerRuleset() when YSLOW is in the beginning. 但是,我不确定当YSLOW开头时如何正确与registerRuleset()通信。 If I put sayHello() in yslow.js I can use it fine, but for any function with YSLOW at the beginning it does not work. 如果我在yslow.js中放了sayHello(),我可以很好地使用它,但是对于开头带有YSLOW的任何函数,它都无法正常工作。 I have tried putting exports before and after YSLOW in a function but have had no success. 我尝试将导出功能放在YSLOW之前和之后,但没有成功。

So my question is, how can I get around this? 所以我的问题是,我该如何解决? And for that matter, what is YSLOW.function() even doing exactly and what is the importance of it? 而且,YSLOW.function()到底在做什么,它的重要性是什么?

Thanks! 谢谢!

I'm not familiar with YSLOW, hence I'm not clear with your query. 我不熟悉YSLOW,因此不清楚您的查询。

If you are trying to check whether YSLOW class objects are loaded, below code may help to identify whether loaded or not loaded. 如果您尝试检查是否已加载YSLOW类对象,则以下代码可能有助于识别是否已加载。 this code will keep polling for the objects to be ready and available. 此代码将继续轮询对象是否准备就绪并可用。 This will poll for 20 milliseconds (you can increase to more). 这将轮询20毫秒(您可以增加到更多)。

Its a Kind of hack, you can keep polling for the objects whether it is loaded and ready to use. 它是一种hack,您可以不断轮询对象是否已加载并准备使用。

   function checkLoaded() {
        if (YSLOW && YSLOW.controller && YSLOW.controller.addRuleset) {
            return true;
        }
        return false;
    }

    /* Start: polling to check if YSLOW Objects are ready */
    var timeout = Date.now() + 10000,
        startTime = Date.now();
    var intervalID = window.setInterval(function () {
        if (checkLoaded()) {
            console.log("GOT Ready at: ", Date.now() - startTime + "ms");
            window.clearInterval(intervalID);
            initLoad();//do your stuffs after loading here.
        } else if (Date.now() > timeout) {
            console.log("Not loaded, kill the polling.");
            window.clearInterval(intervalID);
            failedLoad(); //do your stuff for not loaded here
        }
    }, 20);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM