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