使用RequireJS从数组动态加载模块 [英] Dynamic loading of modules from array using RequireJS

查看:65
本文介绍了使用RequireJS从数组动态加载模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on an application using RequireJS AMD loading method.

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

I have my modules dynamical picked up from a configuration file into an array

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

现在我有了我的requireJS代码

now I have my requireJS code

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

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

Now, the result variable shows the first module which is "module1". How can I get other modules also into variable inside the function() parenthesis.

例如

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

我无法编写上面的硬编码,因为动态变量的数量直到运行时才知道.让我知道如何在函数内部动态捕获对象.

I can't write the above hardcoding because the number of dynamic variables are not known until run time. Do let me know how I can catch the objects dynamically inside the function.

Thx

推荐答案

只需使用 参数 :

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
});

但是,除非您有充分的理由这样做,否则您可能想重新考虑设计应用程序的方式-即使在最顶层,模块也应该简单且可测试.有大量不同的依赖项表明您可能在回调函数中尝试做很多事情.将每个代码路径分解到其自己的模块中,然后仅切换您的顶级依赖关系.在代码中:

However, unless you have a good reason to do so, you probably want to rethink the way you are designing your application - even at the topmost level your modules should be simple and testable. Having a widely varying number of dependencies indicates that you are probably trying to do to much in your callback function. Break each code path out into its own module and then switch only on your top-level dependency instead. In code:

// 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).
});

这篇关于使用RequireJS从数组动态加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆