Dynamic loading of modules from array using Requir

2019-02-06 08:43发布

问题:

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"]

now I have my requireJS code

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

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

For eg,

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

回答1:

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

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


回答2:

Try something like this:

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;

});