2013-03-06 70 views
0

這是我的引導:jQuery的延遲腳本加載,訪問應用程序變量

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); 

     } 
}()); 

可能聽起來很蠢,但如何能安全地訪問我的變量?有沒有最佳做法?你會如何做到這一點?

回答

0

你的問題到底是什麼?如何防止使用未定義的變量?

您可以任意調用之前定義它,它初始化到nullvar appRoot = LanesBoard2010 = null) 或檢查變量調用console.log()if (appRoot) console.log('Status of app access 1: ' + appRoot);)前。

我通常使用第一個建議。 我首先將所有緩存設置爲null,創建自動填充,然後使用$.ajax加載它們,並在加載時更新自動填充源。

+0

不,我無法訪問我的數據。 剛纔找到解決方案: http://stackoverflow.com/questions/10330457/defined-variables-not-working-in-javascript-files-when-i-use-getscript – redflag237 2013-03-06 16:59:33