0

I have a module foo which returns a singleton object. I want to perform some configuration/setup on this module on one part of my page, then use it later on. (Say perhaps the config occurs in some shared partial view).

require(['foo'], function(Foo) {
    Foo.value = 'abc';
});

// Then, later on on the same page...

require(['foo'], function(Foo) {
    alert ('Foo value is ' + Foo.value);
});

So even though RequireJS may execute requires out of order based on when dependencies are loaded, can I be sure that the second call will occur only after the first has finished since they have the same dependencies?

If not, what is a better way to accomplish this?

Tobias J
  • 19,813
  • 8
  • 81
  • 66
  • If you need both references to Foo in the same file, why require it the second time? – marekful May 29 '15 at 22:15
  • Look into their api. in particular, about the config: http://requirejs.org/docs/api.html#config . Also take a look at http://requirejs.org/docs/api.html#config-shim – Dom May 29 '15 at 22:18
  • It really depends on the rest of the code in the file. Which ever block of code is executed first will be called first when the dependencies are resolved. are both of these requires in the same function/scope? – Cory Danielson May 29 '15 at 22:19
  • @CoryDanielson "Which ever block of code is executed first will be called first when the dependencies are resolved." that is a direct contradiction to the answer below; were you able to find someplace in the docs that specifies this? Both `require`s would occur in the same scope, yes -- most likely, the top-level page scope. – Tobias J May 31 '15 at 20:47
  • Ehhhhh, that's annoying. You could force the order by having the second module depend on the first, then. Kind of a hack, though. – Cory Danielson May 31 '15 at 23:56
  • @CoryDanielson yeah, I've considered using the optional "name of module" first parameter to define the config as a separate module, I may go that route if nothing better comes up. – Tobias J Jun 01 '15 at 13:09

1 Answers1

0

Direct answer to question:
Nope, modules with identical dependencies are not guaranteed to execute in order.

From the requireJS docs:

use exports to create an empty object for the module that is available immediately for reference by other modules

but more importantly:

Circular dependencies are rare, and usually a sign that you might want to rethink the design

Source, as this question is very similar.

Community
  • 1
  • 1
Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20
  • I'm not really sure how those doc sections help me solve the problem of defining configuration for a module in a separate call. The exports functionality is specific to the "CommonJS" format of defining modules, which seems quite a bit more cumbersome. This isn't a circular dependency so it doesn't really gain me anything. – Tobias J Jun 01 '15 at 13:07