Nalini Wanjale
Nalini Wanjale

Reputation: 1757

share/use gobal variables in backbone.js using require.js

I have one variable say var tree.I want to use this variable in two files say a.js and b.js.Both files changes state of variable tree.I want to access that variable in other files with change state.How it is possible??

Upvotes: 0

Views: 69

Answers (1)

Steve P
Steve P

Reputation: 19397

There are more elegant ways of doing it, as described in the question linked in the comments, but the simplest way is to define a RequireJS module with an object literal to hold the shared state:

define('sharedstuff', [], {tree: "original value"});

And then from other module you can require it:

require(['sharedstuff'], function(sharedstuff) {
    sharedstuff.tree = "new value";
};

And if from yet another module you require it, RequireJS will not reload a fresh copy but will instead give you the already loaded version with your shared value populated:

require(['sharedstuff'], function(sharedstuff) {
    console.log(sharedstuff.tree) // should be "new value"
};

Upvotes: 1

Related Questions