Reputation: 705
I am trying to create an interface, with same methods, that do same things depending on the device where my web app is running. I would like to create a module empty, and depending on the device, owerwrite that value (I don´t want to load any module that is not neccessary). Currently, I have 3 modules.
First one, once everything is loaded execute the method init from module main:
require( [ "browser", "valueDynamic" ], function( browser, valueDynamic ) {
switch ( browser ) {
case "android":
require( [ "android", "main" ], function( android, main ) {
valueDynamic = android;
main.init();
} );
break;
case "pc":
require( [ "pc", "main" ], function( pc, main ) {
valueDynamic = pc;
main.init();
} );
break;
}
} );
Module valueDynamic, just and empty object that I will overwrite in time execution in previous module:
define(function() {
return {};
} );
And finally module main, with init method:
define( [ "valueDynamic" ],
function( valueDynamic ) {
var main = {};
main.init = function() {
console.log(valueDynamic); // Object empty
};
return main;
}
);
Why valueDinamyc is empty? What am I doing wrong?
Thanks a lot, best regards.
Upvotes: 0
Views: 62
Reputation: 151401
You're using JavaScript incorrectly. The behavior you're seeing is exactly the same as if you ran this pure JavaScript code:
var value = {
// This field is there to distinguish the object from an
// completely empty one. The same demonstration would work if
// value was set to {}.
distinctive: 1
};
function foo(bar) {
console.log("value before", value);
console.log("bar before", bar);
bar = "something";
console.log("bar after", bar);
console.log("value after", value);
}
foo(value);
When foo(value)
is called, bar
is set to refer to the same object as value
. The line bar = "something"
overwrites bar
so that instead of being a reference to an object, it is a string.
The same thing happens with your valueDynamic
module. What you could do is have a field of valueDynamic
hold the platform value:
define(function() {
return { platform: undefined };
} );
And then in your platform detection you do:
valueDynamic.platform = android;
And your do this to dump it to the console:
console.log(valueDynamic.platform);
Upvotes: 1