0

Using RequireJS, how can I simulate typical JS global variables?

Currently I have a module tat simply has named pairs, and I include that module in my main.js module.

Is this a correct way to go about using global variables in RJS?

I had a look at this answer, and the chap is using setters and getters, would I need to do that for all my "globals"? (basically, I have a lot of globals, so it'd mean a huge file in the end)

Or should I look at using the RJS config?

If so, is there a way to change a config variable afterwards? E.G If I want to initially set a URL, but later on I might change it in a module. Is that acceptable/doable?

Community
  • 1
  • 1
Mr Pablo
  • 4,109
  • 8
  • 51
  • 104
  • `require.foo = bar` will give you global scope within the scope of requirejs, not that I'm recommending it however. Your variables should always be scoped to something appropriate. – Brian Driscoll Oct 28 '15 at 14:29

1 Answers1

0

Currently I have a module tat simply has named pairs, and I include that module in my main.js module.

Is this a correct way to go about using global variables in RJS?

That's a perfectly valid option, yes. Any module that requires that name/value pairs module will have access to those "variables" (really they're properties) via the reference it gets from require. Those aren't globals, but they're global to your code.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Granted, bad use of the word global. But you understood me :) With the method I am using, as I have just started and not tested much yet, if Module A changes a "global", will Module B see the global as the new value? Or the original value from the settings module? – Mr Pablo Oct 28 '15 at 14:41
  • You are scoped to your require(...) or define(...), so if you change a "global" value in Module A you will not see that change in Module B, unless Module A is a dependency for Module B (and thus included in the same scope) – Brian Driscoll Oct 28 '15 at 14:58
  • So if the "settings" module is included in every other module, it should work? – Mr Pablo Oct 28 '15 at 15:18
  • @MrPablo: Yes, because a module is only loaded once, so all modules that access it reference the same instance of it. Changing the state of that instance changes the state of the instance, and so is visible through all references to it. – T.J. Crowder Oct 28 '15 at 15:37