0

我有一個運行代碼來初始化一個抽象圖形包。在創建圖形實例後,我從服務器獲取獲取請求的數據,並想更新圖形數據提供者。問題是,有時(對於IE6-8),保存數據提供者的對象尚未初始化,所以當我嘗試更新數據時,JavaScript崩潰。JavaScript:保證對象初始化

在對象準備就緒之前,如何才能執行代碼的延遲? 僞:

... 
... 
... 
// Init code 
$graph = new Graph(); 
... 
... 
... 
// GET request 
$.getJSON(..., ..., function(data) { 
    ... 
    ... 
    ... 
    // Make sure that $graph.series[0] is ready 
    // Should not use while, but something similar in functionality 
    while (!($graph.series && $graph.series[0])) 
    ; // Sleep the code until object is ready 

    // Set the dataprovider after init complete 
    $graph.series[0].setData(data); 
    ... 
    ... 
    ... 
}); 
... 
... 
... 

問候

回答

0

而不是你的while環路(如你確定,不太你想要的),使用setTimeout

$.getJSON(..., ..., function(data) { 
    processData(); 
    function processData() { 
     if (!($graph.series && $graph.series[0])) { 
      // Not ready yet, schedule to try again in a moment 
      // and quit 
      setTimeout(processData, 0); 
      return; 
     } 

     // It's there, process 
     $graph.series[0].setData(data); 
    } 
}); 

延遲將超過0毫秒,當然(一般不低於5-10),但它給其他代碼的機會來初始化對象爲您服務。您可能想要添加超時,以便在出現問題時不會永久循環。

似乎有些奇怪,我們仍然可以連我們從getJSON回報回調之後訪問data,但我們不能因爲processData關閉在回調的背景下,所以它有一個範圍內的持久參考一切都在範圍(包括data)。更多:Closures are not complicated

0

幾天前我做了類似的事情。在此代碼中,我正在驗證對象gAuto已用所需屬性初始化。希望能幫助到你。

function check(callback) { 
    if (gAuto.hasOwnProperty('gm_accessors_')) { 
     callback(); 
    } else { 
     console.log('waiting for init'); 
     init(callback); 
    } 
} 

function init(callback) { 
    console.log('initializing'); 
    setTimeout(function() { 
     check(callback); 
    }, 1); 
} 

init(function() { 
    console.log('init done!'); 
      // access 'gm_accessors_' here 
});