Javascript - 在Require.js中延迟模块返回/声明?

时间:2013-09-11 19:25:35

标签: javascript json requirejs amd

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

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

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

The live code can be seen here

这是我的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();

} );

这是我的lib中的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"

'undefined'来自我从一个不同的模块调用我的Atlas模块时,取决于Atlas模块。

我不确定Atlas模块是否应该在它之前返回一些东西,或者其他模块在返回之前将Atlas模块声明为变量。

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

我对Require.js和AMD完全陌生:这种方法本身存在缺陷吗?我认为将AMD与加载敏感模块结合使用很常见。

感谢您的帮助。

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

1 个答案:

答案 0 :(得分:3)

好的,我检查了你的代码,并提出了一些意见。

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

  • 我也会尝试使用延迟/承诺方法而不是回调。同样,图书馆会帮助你。 jQuery has these for ajax,与when.js等其他库一样。

因此,考虑到这一点,您可能希望看到some jsfiddle code,这可能会给您一些想法。

首先,在一个新模块中有一个ajax抽象,它使用when.js延迟。根据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"}