【问题标题】:JavaScript: Guarantee object initializedJavaScript:保证对象已初始化
【发布时间】:2011-10-24 19:09:10
【问题描述】:

我正在运行一个初始化抽象图形包的代码。创建图形实例后,我使用来自服务器的 get 请求获取数据,并希望更新图形数据提供者。问题是有时(对于 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);
  ...
  ...
  ...
});
...
...
...

问候

【问题讨论】:

    标签: javascript jquery internet-explorer cross-browser internet-explorer-6


    【解决方案1】:

    使用setTimeout,而不是while 循环(正如您所确定的,不是您想要的)。

    $.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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多