1

RequireJS にモジュールがあります。

define(['jquery', 'jsonLoader'], function($, jsonLoader){

function buildMenu()
{   
    jsonLoader('system/models/build/menu.json', function(data){
        var output='';
        // ...
        return output;
    });

}    

return {
    buildMenu : buildMenu
}
 })

関数実行後buildMenu()は「undefined」を返します(で定義したコールバックが実行されjsonLoader()ないため)。ここで関数を呼び出しています:

define(["jquery", "core", "template", "jsonLoader", "debugger"], function($, core, template, jsonLoader) {

var config,
    debug; 

$(function() {             
    jsonLoader('system/config.json',function(data){
        config = data;
        init();
    });
});

function init()
{
    debug = new $.fn.debug;        

    if(config.application.debug == true)
        debug.enabled = true

    // Build menu
    debug.log("Building Menu...");
    console.log ( template.buildMenu() );
}
 });

jsonLoader は次のようになります。

define(["jquery"],function($){

 return function(name, callback){
           $.get(name, function(data){
              callback(data);
           });   
  };

});

どこが間違っていますか?

4

1 に答える 1

1
define(['jquery', 'jsonLoader'], function($, jsonLoader){

    function buildMenu(callback)
    {   
        jsonLoader('system/models/build/menu.json', function(data){
            var output='';
            // ...
            callback(output);
        });

    }    

    return {
        buildMenu : buildMenu
    }
});

そして、あなたがそれを呼ぶ場所

define(["jquery", "core", "template", "jsonLoader", "debugger"], function($, core, template, jsonLoader) {

    ...

    function init()
    {
        ...
        template.buildMenu(function(output) { console.log(output); } );
    }
});

Promise の紹介

ここで、このコールバックのすべてをさらにネストすると、手に負えなくなる可能性があります。jQuery Deferred を使用すると、次のようになります。

define(['jquery', 'jsonLoader'], function($, jsonLoader){

    function buildMenu()
    {
        var d = $.Deferred();
        jsonLoader('system/models/build/menu.json', function(data){
            var output='';
            // ...
            d.resolve(output);
        });
        return d.promise();
    }

    return {
        buildMenu : buildMenu
    }
});

define(["jquery", "core", "template", "jsonLoader", "debugger"], function($, core, template, jsonLoader) {

    var config,
        debug; 

    $(function() {             
        jsonLoader('system/config.json').success(function(data){
            config = data;
            init();
        });
    });

    function init()
    {
        debug = new $.fn.debug;        

        if(config.application.debug == true)
            debug.enabled = true

        // Build menu
        debug.log("Building Menu...");
        console.log ( template.buildMenu().success(function(output){console.log(output);}) );
    }
});

define(["jquery"],function($){

    return function(name){
        var d = $.Deferred();
        $.get(name, function(data){
            d.resolve(data);
        });
        return d.promise();
    };
});
于 2013-06-11T17:46:14.257 に答える