使用RequireJS从数组动态加载模块

Dynamic loading of modules from array using RequireJS

本文关键字:加载 模块 动态 数组 RequireJS 使用      更新时间:2023-09-26

我正在使用RequireJS AMD加载方法开发一个应用程序。

我把我的模块动态地从配置文件中提取到阵列中

var amd_modules = ["module1", "module2","module3"]

现在我有了我需要的JS代码

require(amd_modules, function(result) {
console.log("All modules loaded");
}

现在,结果变量显示第一个模块,即"module1"。如何将其他模块也放入function()括号内的变量中。

例如

require(amd_modules, function(module1, module2, module3) { //
}

我不能写上面的硬编码,因为直到运行时才知道动态变量的数量。请告诉我如何在函数中动态捕捉对象。

Thx

只需使用arguments:

require(amd_modules, function() {
    console.log("All modules loaded");
    // arguments should now be an array of your required modules
    // in the same order you required them
});

然而,除非你有充分的理由这样做,否则你可能需要重新思考你设计应用程序的方式——即使在最高层,你的模块也应该简单且可测试。依赖项的数量变化很大,这表明您可能试图在回调函数中做很多事情。将每个代码路径分解为自己的模块,然后只切换到顶级依赖项。代码中:

// Instead of this:
require(amd_modules, function() {
    console.log("All modules loaded");
    if (complex_condition_A) {
        var x = arguments[0],
                y = arguments[1],
                z = arguments[2];
        // Do things with x, y and z
    }
    else if (complex_condition_B) {
        var a = arguments[0],
                b = arguments[1];
        // Do things with a and b
    }
    else {
        // et cetera, et cetera, et cetera
    }
});

// Do this instead
var rootModule;
if (complex_condition_A) rootModule = "A";
else if (complex_condition_B) rootModule = "B";
else rootModule = "C";
require(rootModule, function(root) {
    // Root has the same API, regardless of which implementation it is
    // This might be as simple as an `init` method that does everything
    // or as complex as, say Facebook's API, but with different libraries
    // loaded depending on the platform the page is loaded on
    // (IE vs. Android for example).
});

试试这样的东西:

define(function () {
    var ClassLoader = function () {
        var _construct = function () {
                return _public;
            },
            _loadClass = function (className, callback) {
                //
                require([className],
                    function (LoadedClass) {
                        callback(LoadedClass);
                    });
            },
            _public = {
                loadClass: _loadClass
            };
        return _construct();
    }
    return ClassLoader;
});