views:

27

answers:

3

I have a jQuery code block for a twitter widget i'm developing ,

$.getJSON("http://twitter.com/users/show.json?screen_name=" + twitterfeed + "&callback=?" ,
    function(data) {    

    var fString = ($('<div id="userimage"><h1>'+ data.followers_count +'</h1></div>').digits()).text();
    var tString = ($('<div id="userimage"><h1>'+ data.statuses_count +'</h1></div>').digits()).text();  

        $('#left-sidebar').prepend('<div id="userimage"><h1>'+ tString +'</h1></div>');
        $('#left-sidebar').prepend('<div id="userimage"><h2>TWEETS</h2></div>');        
        $('#left-sidebar').prepend('<div id="userimage"><h1>'+ fString +'</h1></div>');
        $('#left-sidebar').prepend('<div id="userimage"><h2>FOLLOWERS</h2></div>');
        $('#left-sidebar').prepend('<div id="userimage"><img id="ProfileImageLarge" src=' + data.profile_image_url + '></div>');
    });

I want to grab fString and tString and use them in outside functions.

I also need the value of data.followers_count and data.statuses_count to be passed along with the variable so that value is correct in any function instead of undefined.

A: 
window.fString = fString

Then in your function you can reference window.fString in other functions

cjavapro
+3  A: 

You don't need to put them in a global context using window.fString, you can just move your var declarations outside of the $.getJSON.

In javascript closures will allow access to variables defined outside a function, but any vars defined in the function will not be accessible outside.

var fString, tString;

$.getJSON(... , function(){
  fString = ...;
});

Any functions defined in the same scope s $.getJSON will also have access to fString and tString

brad
A: 

Define these variables anywhere that is in scope for both your getJSON call and the other functions. Ideally you wouldn't define them on the global window object, as that is the most amount of overkill you can get. Additionally, you could attach them as data to some arbitrary part of your markup (I use the <body>). You could do that like so:

$('body').data('fstring', ($('<div id="userimage"><h1>'+ data.followers_count +'</h1></div>').digits()).text());
$('body').data('tString', ($('<div id="userimage"><h1>'+ data.statuses_count +'</h1></div>').digits()).text());

Those values can then be accessed as such:

var fString = $('body').data('fstring');
var tString = $('body').data('tstring');

You could also use .data() to store that data values that come back from your getJSON request, so that those can be accessed later as well.

Here are the docs for .data(): http://docs.jquery.com/Data

And here's a demo of using data to access a value set from another function: http://jsfiddle.net/9zcET/

Ender