javascript - 无法检索数组数据

时间:2013-01-24 10:18:22

标签: javascript arrays mesh

我正在尝试编写一个OBJMesh模型阅读器并且我已经设置了OBJMesh类,但是当我尝试通过创建OBJMesh对象并调用get函数来检索数组中存储的数据时,它不会做到这一点。

这是代码

OBJMesh.js

function OBJMesh(file)
{
    this.modelVertex = [];
    this.modelColor = [];
    this.init = false;

    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);

    var objmesh = this;
    rawFile.onreadystatechange = function ()
    {

        if(rawFile.readyState == 4)
        {
            if(rawFile.status === 200 || rawFile.status === 0)
            {
                var allText = rawFile.responseText;
                var lines = allText.split("\n");


                for(var i = 0; i < lines.length; i ++)
                {
                    var lineData = lines[i];
                    var lineString = lineData.split(" ");

                    if(lineString[0] === "v")
                    {

                        var x = parseFloat(lineString[1]);
                        var y = parseFloat(lineString[2]);
                        var z = parseFloat(lineString[3]);

                        objmesh.modelVertex.push(x);
                        objmesh.modelVertex.push(y);
                        objmesh.modelVertex.push(z);

                        objmesh.modelColor.push(0.0);
                        objmesh.modelColor.push(0.0);
                        objmesh.modelColor.push(0.0);
                        objmesh.modelColor.push(1.0);

                        //document.getElementById("textSection").innerHTML = objmesh.modelVertex[0];
                    }
                }
            }
        }
        objmesh.init = true;
    }

    rawFile.send();
}

OBJMesh.prototype.getModelVertex = function ()
{
    return this.modelVertex;
};

OBJMesh.prototype.getModelColor = function ()
{
    return this.modelColor;
};

OBJMesh.prototype.getInit = function ()
{
    return this.init;
};

main.js

var cubeModel;

function main()
{
    cubeModel = new OBJMesh("file:///Users/DannyChen/Desktop/3DHTMLGame/cube.obj");

    while(cubeModel.getInit() === false)
    {
        //wait for it
    }

    var cubeVertex = cubeModel.getModelVertex();

    document.getElementById("textSection").innerHTML = cubeVertex[0];

}

它只是打印出“未定义”。为什么?我该如何解决?

1 个答案:

答案 0 :(得分:1)

但似乎onreadystatechange是一个异步调用,所以,

this.init = true;

将在调用onreadystatechange函数之前设置。

可能是你可以在onreadystatechange函数结束时设置

objmesh.init = true;

我希望这有帮助

相关问题