私はこの質問が何度か聞かれたことを知っていますが、前の質問のどれでも私のために働く解決策を見つけることができなかったようです。HTMLページの読み込みが完了すると設定される変数がありますが、コードがその変数にアクセスしようとすると、未定義であると表示されることがあります。すべてが正しく読み込まれるのを待っていると思うので、理由はわかりません。ほとんどの場合、すべてのコードが正常に実行されるため、この例外はランダムに発生するようです。これが私のコードの簡略化されたバージョンです:
var globalVar;
function initStuff(filePath) {
// I wait till the HTML page is fully loaded before doing anything
$(document).ready(function(){
var video = document.getElementById("videoElementID");
// My parseFile() function seems to run smoothly
var arrayOfStuff = parseFile(filePath);
if (arrayOfStuff == null) {
console.error("Unable to properly parse the file.");
} else {
setGlobalVariable(arrayOfStuff);
video.addEventListener("play", updateVideoFrame, false);
}
});
}
function setGlobalVariable(arrayOfStuff) {
window.globalVar = arrayOfStuff;
}
function updateVideoFrame() {
// A bunch of other code happens first
// This is the line that fails occasionally, saying
// "window.globalVar[0].aProperty.anArray[0] is undefined"
var test = window.globalVar[0].aProperty.anArray[0].aProperty;
}
この問題を引き起こしている可能性があると私が考えることができる唯一のことは、ある種の同期性の問題です。しかし、なぜそうなるのかわかりません。助けてください!
編集:
非同期性の問題が私のparseFile(xmlFile)
方法に起因する場合、これが私がそこで行っていることです。メソッドを強制的に同期的に実行するため、問題が発生している可能性はないと思いましたが、間違っている場合は、次のようになります。
function parseKML(xmlFile) {
var arrayOfStuff = new Array();
// Turn the AJAX asynchronicity off for the following GET command
$.ajaxSetup( { async : false } );
// Open the XML file
$.get(xmlFile, {}, function(xml) {
var doc = $("Document", xml);
// Code for parsing the XML file is here
// arrayOfStuff() gets populated here
});
// Once I'm done processing the XML file, I turn asynchronicity back on, since that is AJAX's default state
$.ajaxSetup( { async : true } );
return arrayOfStuff;
}