开发者

Javascript: How to make this var. work globally

I am having an issue with this variable not wanting to work outside the function and I just can't understand why! here's the code:

globalData = new Array();

 // 
 // Colors
 //
 if ( settings.category == 'colors' ) {
  $.getJSON(colorLoversURL, function(data) {
   for ( var i in data ) {
    var localData = data[i].hex;
    globalData.push(localData);
   }
  });
 }

 // 
 // Palettes
 //
 else if ( settings.category == 'palettes' ) {
  $.getJSON(colorLoversURL, function(data) {
   for ( var i in开发者_如何学编程 data ) {
    var localData = new Array();
    for ( var j in data[i].colors ) {
     localData.push(data[i].colors[j]);
    }
    globalData.push(localData);
   }
  });
 }

Now the thing is that globalData is only keeping the values inside the getJSON function and out of the function, when I need it, It just comes up blank (I test the values in an alert window). I also tried taking the 'var' on and off the front of the code. Is there something wrong here?


When are you inspecting globalData?

both calls to getJSON uses a callback to manipulate globalData so the function might not be called yet before you inspect globalData. Don't forget that you're using asynchronous javascript there.

If it is the case, I recommend using function chaining

 function useGlobalData() {
    alert(globalData); 
    //do other stuff
 }
 // 
 // Palettes
 //

  $.getJSON(colorLoversURL, function(data) {
   for ( var i in data ) {
    var localData = new Array();
    for ( var j in data[i].colors ) {
     localData.push(data[i].colors[j]);
    }
    globalData.push(localData);
    useGlobalData();
   }
  });


If it's on your .js file, then the very 1st line must be var globalData = new Array();

or if it's inside <script type="text/javascript">...</script> then your very next line will be

var globalData = new Array();

E.g.

<script type="text/javascript">
   var globalData = new Array();
   //Rest of JS code...
   function whatever() {

   }
</script>

then globalData becomes global.


This should work. Is it possible that the code runs twice somehow, causing globalData to be reset back to an empty array?


You are operating inside a javascript closure, and inside a closure you have a distinct scope.

What this means is that only stuff defined within the scope will be accessible to you.

simply saying x = something() does not create a global ( a variable that will be accessible from all scopes ).

TO do that you need to do var x = something();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜