Eugene Shmorgun
Eugene Shmorgun

Reputation: 2075

Correctly set global variable from JavaScript

I have the simple code:

<script type="text/javascript">

var dataFromBrowser;
var dataForStore = [];

var callServerOwnerId = { 
  callback:callbackFunction, 
  arg: dataFromBrowser 
};
// call to DWR function - from Java
AssetScreener.getEntityOwnerIds(callServerOwnerId);


function callbackFunction(dataFromServer, arg1) {
 // yes, I see what I need
 alert(dataFromServer);
 return dataForStore[0] = dataFromServer[0];

}



console.log(dataForStore);

The problem is that I need to retrieve data from my callbackFunction and set data to dataForStore ?

Upvotes: 0

Views: 124

Answers (2)

Abraham P
Abraham P

Reputation: 15471

In javascript setting a global variable is as simple as ommitting the var keyword.

For example:

 var someVar = 5

 function foo(){
      someVar = someVar + 1;
 }   

Will produce undefined while

 someVar = 5;

 function foo(){

      someVar = someVar+1;
 }

Will produce 6. Note that generally speaking (there are of course exceptions), if you're using global variables you're doing it wrong.

Upvotes: 2

Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

Remove the var before dataForStore , and it will become a global variable.

Upvotes: 1

Related Questions