0

I have a Javascript object that I use for global variables, username, userid, etc.. I call it myGlobals. I have a need to load another object via jQuery (application preferences) that I will also need to access globally. For cleanliness, I want it to be a part of myGlobals.

I see posts on how to "merge" the two objects, or add the second one as an array, but that is not exactly what I want. I have this:

    var appPref = JSON.parse(xhr.responseText); //this works fine
    myGlobals.appPref = appPref; // this does not

I want to be able to do something like this:

    alert(myGlobals.appPref.messages.hello);

but I am getting a "myGlobals.appPref: is undefined.

How do I do this? I am using jQuery if there is some magic in there that I could use.

mmaceachran
  • 3,178
  • 7
  • 53
  • 102
  • 3
    I am betting this is an asynchronous issue. You are probably trying to eat the pizza before the delivery guy has delivered it to your house. Ajax calls are asynchronous and you are probably reading the value before it has been returned from the server. That is why we have clalbacks. You need to do the logic in the callback. http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – epascarello Dec 30 '15 at 02:58
  • So are you loading the data via an Ajax call? – epascarello Dec 30 '15 at 03:01

1 Answers1

2
myGlobals.appPref = appPref;

This is how you do it.

The problem is somewhere else. Try to put a console.log(appPref); before this line. Most likely it will show undefined.

lleaff
  • 4,249
  • 17
  • 23