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
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).
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With