2013-03-01 4 views
0

작동하도록 코드를 가져 오는 데 문제가 있습니다. 로드 및 잘 작동하는 XMLHttpRequest 사용하여 JSON 파일을 구문 분석하지만 내 setup() 함수를 spriteDictionary 같은 정의한 변수 중 하나를 다른 함수를 호출 할 수 없습니다 후 - 비록 다양한 설치 함수 이 변수를 읽을 수 있고 모두 좋아 보인다.자바 스크립트 변수가 정의되지 않음

의견이 있으십니까? 아래 예제에서 console.log (parsedJSON)를 호출 할 때; 그것은 내 설치 코드에서 그 내용을 읽을 수 있기 때문에 그것은 이상한 어떤 정의되지 않은 온다. 감사!

<!DOCTYPE html> 

<html> 
<head> 
<title>Page Title</title> 
</head> 
<body id="body"> 
</body> 

<script type="application/x-javascript"> 
var parsedJSON; 
var ctx; 
var canvas; 
var atlas; 
var sprites = []; 
var spriteDictionary = {}; 

var sprite = function(name, atl, x, y, w, h) { 
    this.name = name; 
    this.atlas = atl; 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h; 
    this.cx = -w/2.0; 
    this.cy = -h/2.0; 

} 

function setup() { 
    var body = document.getElementById("body"); 

    canvas = document.createElement("canvas"); 
    canvas.width = 1200; 
    canvas.height =720; 
    body.appendChild(canvas); 

    var ctx = canvas.getContext('2d'); 

    ctx.fillStyle="#000000"; 
    ctx.fillRect(0,0,1200,720); 

    var xhr = new XMLHttpRequest(); 
    xhr.open("GET","game_gfx.json",true); 
    xhr.onload = function(){ 
     parsedJSON = JSON.parse(this.responseText); 
     load_assets(parsedJSON); 
    } 
    xhr.send(); 
    ctx = canvas.getContext('2d'); 

} 

function load_assets(pJSON) { 
    atlas = new Image(); 
    atlas.onload = function() { 
     console.log("atlas loaded"); 
    } 
    atlas.src= pJSON['meta']['image']; 
    var frame; 
    for (var i in pJSON['frames']){ 
     frame = pJSON['frames'][i]; 
     spriteDictionary[frame['filename']] = new sprite(frame['filename'],atlas,frame['frame']['x'],frame['frame']['y'],frame['frame']['w'],frame['frame']['h']); 
     i++; 
    } 
} 

setup(); 

console.log(parsedJSON); 

</script> 


</html> 
+0

'유형 = "응용 프로그램/X-자바 스크립트"'의 목적은 무엇과 같을 것이다? 그냥 내버려둬. –

+0

목적은 komodo-edit가 자동으로 그것을 던져 버렸고 나는 그것을 제거하기에는 너무 게을 렀다. – Lucian

답변

1

비동기 호출은 동기식으로 처리 할 수 ​​없습니다.

Ajax 호출이 리턴되기 전에 console.log 행을 호출 중입니다.

onload listener의 간단한 console.log 문이 표시됩니다.

xhr.onload = function(){ 
    console.log("I AM HERE!"); 
    ... 

로그는

undefined 
"I AM HERE" 
"atlas loaded" 
+0

Ahhh Thanks. 그래서 다른 명령을 호출 할 때 내 XHR이 finsished하지 않았습니다. 도움에 감사드립니다. – Lucian

관련 문제