12

我有一个模块,它返回一个由 JSON 数据和图像对象组成的数组。由于加载 JSON(从其他文件)和图像对象都需要时间,我需要我的模块只在两者都完成后才返回数组。

目前,该模块总是在其他模块中返回“未定义”,我相信这是因为该模块没有像我期望的那样等待返回(但我不确定)。或者,因为使用此 Atlas 模块的其他模块在返回任何内容之前将其声明为变量。

编辑以显示我如何定义/需要模块 *再次编辑以显示更多代码*

可以在这里看到实时代码

这是我的 tile-atlas 模块:

define( function() {

var tilesheetPaths = [
            "tilesheets/ground.json",
    "tilesheets/ground-collision.json",
    "tilesheets/objects-collision.json"
];

var tileAtlas = [ ];


function loadAtlasJSON() {  
    for (var i = 0; i < tilesheetPaths.length; i++) {
        loadJSON( 
            {
                fileName: tilesheetPaths[ i ],
                success: function( atlas ) {            
                    addToTileAtlas( atlas );
                }
            } 
        );
    }
};


function addToTileAtlas( atlas ) {
    atlas.loaded = false;
    var img = new Image();

    img.onload = function() {
        atlas.loaded = true;
    };

    img.src = atlas.src;

    // Store the image object as an "object" property
    atlas.object = img;
    tileAtlas[ atlas.id ] = atlas;
}


// Returns tileAtlas[ ] once everything is loaded and ready
function tileAtlasReady() {
    if ( allJSONloaded() && allImagesLoaded() ) {
        console.log("TileAtlas ready"); 
        return tileAtlas;
    }
    console.log("TileAtlas not ready");
    setTimeout(tileAtlasReady, 10);
};


// Checks to make sure all XMLHttpRequests are finished and response is added to tileAtlas
function allJSONloaded() {
    // If the tilesheet count in tileAtlas !== the total amount of tilesheets
    if ( Object.size(tileAtlas) !== tilesheetPaths.length ) {
        // All tilesheets have not been loaded into tileAtlas
        console.log("JSON still loading");
        return false;
    } 
    console.log("All JSON loaded");
    return true;
};


// Checks that all img objects have been loaded for the tilesheets
function allImagesLoaded() {
    for ( var tilesheet in tileAtlas ) {
        if (tileAtlas[tilesheet].loaded !== true) {
            console.log("Images still loading");
            return false;
        }
    }
    console.log("All images loaded");
    return true;
};


// Loads the JSON/images
loadAtlasJSON();

// Module should only return when tileAtlasReady() returns
return tileAtlasReady();

} );

这是我的库中的 loadJSON 函数:

window.loadJSON = function( args ) {
    var xhr = new XMLHttpRequest();
    xhr.overrideMimeType( "application/json" );
    xhr.open( "GET", args.fileName, true );

    xhr.onreadystatechange = function () {
        if ( xhr.readyState == 4 ) {        

            if ( xhr.status == "200" ) {
                // Check that response is valid JSON
                try {
                    JSON.parse( xhr.responseText );
                } catch ( e ) {
                    console.log( args.fileName + ": " + e );
                    return false;
                }
                args.success( JSON.parse(xhr.responseText) );
            // xhr.status === "404", file not found
            } else {
                console.log("File: " + args.fileName + " was not found!");
            }
        }
    }
    xhr.send();
}   

以及加载我的 tile-atlas 模块的模块:

define( ['data/tile-atlas'], function( tileAtlas ) {

function displayImages() {
    // Code
};

// Returns undefined
console.log(tileAtlas);

displayKey();

} );

这是输出的样子:

[12:14:45.407] "JSON still loading"
[12:14:45.407] "TileAtlas not ready"
[12:14:45.408] undefined 

[12:14:45.428] "JSON still loading"
[12:14:45.428] "TileAtlas not ready"

[12:14:45.469] "All JSON loaded"
[12:14:45.470] "Images still loading"
[12:14:45.470] "TileAtlas not ready"

[12:14:45.481] "All JSON loaded"
[12:14:45.481] "Images still loading"
[12:14:45.481] "TileAtlas not ready"

[12:14:45.492] "All JSON loaded"
[12:14:45.492] "All images loaded"
[12:14:45.492] "TileAtlas ready"

“未定义”来自当我从另一个模块控制台.log 我的 Atlas 模块时,这取决于 Atlas 模块。

我不确定是 Atlas 模块提前返回了某些东西,还是其他模块在返回某些东西之前将 Atlas 模块声明为变量。

但是如果是后者,有没有办法让模块在它们的依赖项完成返回某些东西之前不会运行?

我对 Require.js 和 AMD 完全陌生:这种方法是否存在固有缺陷?我认为将 AMD 与加载敏感模块一起使用是很常见的。

谢谢你的帮助。

编辑 查看另一个游戏的源代码,我意识到我可以使用 require.js 文本插件加载我的 JSON 文件,而不是在我的模块中实现 XHR。这要简单得多,因为我不需要处理在模块中等待 XHR 的复杂性。 以下是 BrowserQuest 的做法

4

1 回答 1

3

好的,我检查了您的代码并进行了一些观察。

  • 除非您确切知道自己在做什么(或者这样做是为了了解 XHR),否则我不会XMLHttpRequest直接使用。这个对象有几个跨浏览器的陷阱,所以我会使用一个 JS 库来帮助解决这个问题,jQuery 是最明显的一个。

  • 我也会尝试使用延迟/承诺方法而不是回调。同样,图书馆将在这里帮助您。jQuery 为 ajax 提供了这些,就像when.js等其他库一样。

所以考虑到这一点,这里有一些你可能想看的 jsfiddle 代码,它可能会给你一些想法。

首先,新模块中有一个 ajax 抽象,它使用 when.js deferreds。该模块将根据 XHR 是否成功来解决或拒绝延迟。注意我已经离开了直接使用 XHR,但我建议使用 JS 库。

// --------------------------------------------------
// New module
// Using https://github.com/cujojs/when/wiki/Examples
// --------------------------------------------------

define("my-ajax", ["when"], function (when) {
    // TODO - Fake id only for testing
    var id = 0;

    function makeFakeJSFiddleRequestData(fileName) {
        var data = {
            fileName: fileName
        };
        data = "json=" + encodeURI(JSON.stringify(data));
        var delayInSeconds = Math.floor(8 * Math.random());
        data += "&delay=" + delayInSeconds;
        return data;
    }

    return function loadJSON(args) {
        // Create the deferred response
        var deferred = when.defer();

        var xhr = new XMLHttpRequest();
        xhr.overrideMimeType("application/json");

        var url = args.fileName;

        // TODO - Override URL only for testing
        url = "/echo/json/";

        // TODO - Provide request data and timings only for testing
        var start = +new Date();
        var data = makeFakeJSFiddleRequestData(args.fileName);

        // TODO - POST for testing. jsfiddle expects POST.
        xhr.open("POST", url, true);

        xhr.onreadystatechange = function () {
            // TODO - duration only for testing.
            var duration = +new Date() - start + "ms";
            if (xhr.readyState == 4) {
                if (xhr.status === 200) {
                    // Check that response is valid JSON
                    var json;
                    try {
                        json = JSON.parse(xhr.responseText);
                    } catch (e) {
                        console.log("rejected", args, duration);
                        deferred.reject(e);
                        return;
                    }
                    console.log("resolved", args, duration);
                    // TODO - Fake id only for testing
                    json.id = ("id" + id++);
                    deferred.resolve(json);
                } else {
                    console.log("rejected", args, duration);
                    deferred.reject([xhr.status, args.fileName]);
                }
            }
        }

        // TODO - Provide request data only for testing
        xhr.send(data);

        // return the deferred's promise.
        // This promise will only be resolved or rejected when the XHR is complete.
        return deferred.promise;
    };
});

现在您的 atlas 模块看起来有点像这样(为清楚起见,删除了图像代码):

// --------------------------------------------------
// Your module
// Image stuff removed for clarity.
// --------------------------------------------------

define("tile-atlas", ["my-ajax", "when"], function (myAjax, when) {

    var tilesheetPaths = [
        "tilesheets/ground.json",
        "tilesheets/ground-collision.json",
        "tilesheets/objects-collision.json"];

    // TODO - Changed to {} for Object keys
    var tileAtlas = {};

    function loadAtlasJSON() {
        var deferreds = [];
        // Save up all the AJAX calls as deferreds
        for (var i = 0; i < tilesheetPaths.length; i++) {
            deferreds.push(myAjax({
                fileName: tilesheetPaths[i]
            }));
        }
        // Return a new deferred that only resolves
        // when all the ajax requests have come back.
        return when.all(deferreds);
    };

    function addToTileAtlas(atlas) {
        console.log("addToTileAtlas", atlas);
        tileAtlas[atlas.id] = atlas;
    }

    function tileAtlasesReady() {
        console.log("tileAtlasesReady", arguments);
        var ajaxResponses = arguments[0];
        for (var i = 0; i < ajaxResponses.length; i++) {
            addToTileAtlas(ajaxResponses[i]);
        }
        return tileAtlas;
    };

    function loadAtlases() {
        // When loadAtlasJSON has completed, call tileAtlasesReady.
        // This also has the effect of resolving the value that tileAtlasesReady returns.
        return when(loadAtlasJSON(), tileAtlasesReady);
    }

    // Return an object containing a function that can load the atlases
    return {
        loadAtlases: loadAtlases
    };
});

您的应用程序(或我的假演示)可以通过以下方式使用此代码:

// --------------------------------------------------
// App code
// --------------------------------------------------

require(["tile-atlas"], function (atlas) {
    console.log(atlas);

    // The then() callback will only fire when loadAtlases is complete
    atlas.loadAtlases().then(function (atlases) {
        console.log("atlases loaded");
        for (var id in atlases) {
            console.log("atlas " + id, atlases[id]);
        }
    });
});

并将以下类型的信息转储到控制台:

Object {loadAtlases: function}
resolved Object {fileName: "tilesheets/ground-collision.json"} 3186ms
resolved Object {fileName: "tilesheets/ground.json"} 5159ms
resolved Object {fileName: "tilesheets/objects-collision.json"} 6221ms
tileAtlasesReady     [Array[3]]
addToTileAtlas Object {fileName: "tilesheets/ground.json", id: "id1"}
addToTileAtlas Object {fileName: "tilesheets/ground-collision.json", id: "id0"}
addToTileAtlas Object {fileName: "tilesheets/objects-collision.json", id: "id2"}
atlases loaded
atlas id1 Object {fileName: "tilesheets/ground.json", id: "id1"}
atlas id0 Object {fileName: "tilesheets/ground-collision.json", id: "id0"}
atlas id2 Object {fileName: "tilesheets/objects-collision.json", id: "id2"}
于 2013-09-12T08:57:31.020 回答