Roman
Roman

Reputation: 4513

A local/global variable in RequireJS

I'd like to create a variable that will be accessible from any module inside my RequireJS project.

For example, on init I'd like to set:

this.myVar = 123;

and be able to access it in any other module inside (but not outside) my RequireJS project such as:

console.log(this.myVar);

Is this possible?

P.S - I'm using 'this' just for an example. Any other option is viable.

P.S 2 - The RequireJS is actually a widget that can be instantiated several times such as :

new Widget('w1');
new Widget('w2');

and the global parameter should be inside each instance and not shareable between them.

EDIT (Example for such possible code, which doesn't work):

define('module1', [], function() {
    var myVar = 123;
});

define('module2', ['module1'], function(m1) {
    console.log(myVar); // Should print '123'
});

Upvotes: 1

Views: 183

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

Create a Settings module and whoever needs to access the settings imports it - have it export an object with whatever variables you want.

Upvotes: 2

Related Questions