javascript - Setting and getting global variable with Require.js -



javascript - Setting and getting global variable with Require.js -

i'm using require.js , backbone.js. i'm trying set variable , utilize in multiple views throughout app calling module containing variable require. module is:

define(function (require) { "use strict"; var variable_a = "aaa", variable_b ="bbb" ; var some_variables = (function () { homecoming { setvariablea: function (x) { variable_a = x; }, return_a: variable_a, return_b: variable_b }; })(); homecoming some_variables; });

in view, include module , set variable, check has been set:

somevariables.setvariablea('456'); console.log('somevariables.return_a '); console.log(somevariables.return_a);

but returns "aaa" rather "456". doing wrong?

this mutual fact javascript. when separate scope, i.e., write like

(function(){ ... })()

this kid scope gets re-create of parent scope. since have primitive info types (e.g. string) in parent scope, kid scope holds re-create of primitive data. changes create in kid scope not reflected in parent scope.

the work around changing primitive info object kid holds reference. example

define(function (require) { "use strict"; var variables = { : "aaa", b : "bbb" }; var some_variables = (function () { homecoming { setvariablea: function (x) { variables.a = x; }, return_variables: variables }; })(); homecoming some_variables; });

and phone call changed

some_variables.setvariablea('456'); console.log('somevariables.return_a '); console.log(some_variables.return_variables.a);

this give 456 expected.

javascript backbone.js requirejs global-variables

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -