TonyTakeshi
TonyTakeshi

Reputation: 5929

RequireJS - Using both define and require under same function scope

Would like to know is it possible to use both define and require under same function scope. Usually is either require or define, how do I have both under same scope?

define(["my/cart", "my/inventory"],
    function(cart, inventory) {
        //Define foo/title object in here.
   }
);

require(["some/module", "a.js", "b.js"], function(someModule) {
    //This function will be called when all the dependencies
    //listed above are loaded. Note that this function could
    //be called before the page is loaded.
    //This callback is optional.
}); 

Upvotes: 0

Views: 1911

Answers (1)

Gabriel Jürgens
Gabriel Jürgens

Reputation: 3153

The define function is for "defining" modules with dependencies using AMD style, and require is mostly used to call those modules previously defined with define function.

The recommended practice is to define only one module per file, but you can add more than one define if you pass the name of the module as the first argument to that function.

If you pass the name explicitly to the define function you can nest define inside a require call, but it will make no sense, because all the dependencies passed to the require can be passed to the define directly, which is faster an clearer than nesting defines inside requires.

Maybe, nesting a require inside a define could be more useful, perhaps if you have a module with dependencies that are only required under certain conditions, it could make sense to add the common dependencies on the define function, and the more specific ones with a require inside a conditional statement.

In my opinion the important concept is to understand that basically define is for defining AMD modules, and require is for calling them. (you can use non AMD files as dependencies but this is other matter.)

Upvotes: 3

Related Questions