保证对象初始化



我有一个初始化抽象图形包的代码在运行。创建图形实例后,我从服务器获取数据请求,并希望更新图形数据提供程序。问题是,有时(对于IE6-8)持有数据提供程序的对象还没有初始化,所以当我试图更新数据时,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);
  ...
  ...
  ...
});
...
...
...

而不是您的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),但它给了其他代码一个机会来初始化该对象。你可能想要添加一个超时,这样你就不会在出现问题时永远循环。

这似乎很奇怪,我们仍然可以访问data,即使我们从getJSON回调返回后,但我们可以,因为processData是一个闭包回调的上下文中,所以它有一个持久的引用在该上下文中范围内的一切(包括data)。闭包并不复杂

几天前我也做过类似的事情。在这段代码中,我正在验证对象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
});

最新更新