Imagine this is your module…
define(['Utils/css'], function(css){
console.log(css);
});
If your Utils/css
dependancy was like the following…
define(['require'], function(require){
return {
style: require('Utils/CSS/getAppliedStyle'),
classes: require('Utils/CSS/getArrayOfClassNames'),
add: require('Utils/CSS/addClass'),
remove: require('Utils/CSS/removeClass'),
has: require('Utils/CSS/hasClass')
}
});
…then you would have this error displayed: Uncaught Error: Module name 'Utils/CSS/getAppliedStyle' has not been loaded yet for context: _
because you created a race condition issue.
One work around would be to do…
define(['Utils/CSS/getAppliedStyle', 'Utils/CSS/getArrayOfClassNames', 'Utils/CSS/addClass', 'Utils/CSS/removeClass', 'Utils/CSS/hasClass'], function(getAppliedStyle, getArrayOfClassNames, addClass, removeClass, hasClass){
return {
style: getAppliedStyle,
classes: getArrayOfClassNames,
add: addClass,
remove: removeClass,
has: hasClass
}
});
But that's FUGLY, so instead, go back to what we had before but just don't specify require
as a dependancy…
define(function(require){
return {
style: require('Utils/CSS/getAppliedStyle'),
classes: require('Utils/CSS/getArrayOfClassNames'),
add: require('Utils/CSS/addClass'),
remove: require('Utils/CSS/removeClass'),
has: require('Utils/CSS/hasClass')
}
});
I have an idea of why this works but maybe @jrburke can clarify.
it would work even if the module "Utils/CSS/getAppliedStyle" was loaded by another module, RequireJS creates another context only if you use the multiversion feature, but by default all modules are loaded on the root (
_
) context -requirejs.s.contexts._.defined
contains a reference to all the defined modules on the_
context, so when yourequire('foo')
it will check if the modulefoo
is on this list and if so return it, otherwise throw the error you saw on the first example.here is how requirejs does the CJS "magic": https://github.com/jrburke/requirejs/blob/4cf2e3fcb4/require.js#L1673-1694 - basically if you don't have a dependency array it checks the number or parameters and reads the function content to grab the dependencies.