【问题标题】:jQuery deferred Script loading, Access App VariablejQuery延迟脚本加载,访问应用程序变量
【发布时间】:2013-03-06 16:30:39
【问题描述】:

这是我的引导程序:

LanesBoard2010 = (function () {
    var appRoot = this;

    appRoot.deferredLoad = new Object(); //holding jqxhr states
    appRoot.utils = {}; //namespace for helper classes
    appRoot.models = {};
    appRoot.data = (function () { } ()); //store data from webservices here
    appRoot.app = (function () { } ()); //ViewModel
}();

经过一些初始化后,我运行了我的延迟应用加载器:

function appStart() {
    appRoot.deferredLoad.app = $.getScript('../TaskBoardContent/Script/app/lanesboard.js');
    $.when.apply($, appRoot.deferredLoad.app).then(function () {
        if (window.console)
            if (debug)
                console.log('application lanesdashboard was loaded successfully\n');
    }, function () {
        if (window.console)
            if (debug)
                console.log('fatal error: unable to load application lanesdashboard\n');
    });
};

现在我需要访问appRoot,或者更一般的,修改LanesBoard2010的属性。

以下语句来自我的 lanesboard.js。它只是在第一个 console.log 之后失败,因为我可以看到两个变量名都是未知的:

(function () {
    if (window.console)
        if (true) {
            console.log('App has been initialised successfully');
            console.log('Status of app access 1: ' + appRoot);
            console.log('Status of app access 2: ' + LanesBoard2010);

        }
}());

听起来可能很愚蠢,但我怎样才能安全地访问我的变量?有没有最佳实践?你会怎么做呢?

【问题讨论】:

    标签: performance jquery jquery-plugins js-amd


    【解决方案1】:

    您的问题到底是什么?如何防止使用未定义的变量?

    您可以在任何调用之前定义它并将其初始化为 null (var appRoot = LanesBoard2010 = null) 或在调用 console.log() (if (appRoot) console.log('Status of app access 1: ' + appRoot);) 之前检查变量。

    我通常使用第一个建议。 我首先将所有缓存设置为null,创建自动完成,然后使用$.ajax 加载它们,加载后更新自动完成源。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2013-12-31
    • 2023-04-05
    • 1970-01-01
    • 2016-10-03
    • 2016-05-04
    相关资源
    最近更新 更多