1

Hi i have the following.

var g = new Array() ; 

$.getJSON(google, function(data) {
  var i = 0 ; 
  $.each(data.items, function() {
    var obj = new res(i, this.title, this.snippet, this.formattedUrl, 0) ; 
    g.push(obj) ; 
    i=i+1 ;
  });
});

I need to be able to access the array outside the async function.

3
  • 1
    Please,format your code Commented Mar 12, 2013 at 16:07
  • 1
    If you are using the array outside of the async function, how will you know it is in the correct state? Commented Mar 12, 2013 at 16:08
  • If g is in the same scope as the getJSON call, then your anonymous function is a closure and already has access to g. If it's not in the same scope, you need to post a more detailed description of your code structure. Commented Mar 12, 2013 at 16:10

2 Answers 2

4

Strictly answering the part about how to set up a global, one common way to do this is to create a namespace for your app, like

window.App = {}; // or just App = {};

and then to put global stuff in there

App.g = [];

And now you can access your namespace from anywhere.

Note you still need to be aware of when you might have outstanding requests modifying your global variables.

Sign up to request clarification or add additional context in comments.

1 Comment

Wish I could up vote more than once. This solves a problem I've had for years.
1

you may opt to use the .data() which is simpler than global variables.

The way it works is that you set elements like this :

$('body').data('g', mydata);

anywhere, and retrieve it like this :

$('body').data('g');

Of course it can be on any element, not just body.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.