Justin Meltzer
Justin Meltzer

Reputation: 13548

Scoping issue with javascript callback

I have a function that calls another function and I want to store the returned result in a variable:

function trigger_gridly(){
    var channel_name = get_channel_name();
}

The called function triggers an AJAX request, which triggers a callback receiving JSON:

function get_channel_name(){
    var channel_name;     
    $.getJSON(APPLICATION_DOMAIN + "channels/new.json?callback=?", null, handleJson);
}

function handleJson(channel){
    var channel_name = channel.name;
    return channel_name;
}

The problem is that the channel_name in trigger_gridly() does not receive the value of channel_name in the handleJson callback function. How can I expose the data in the callback to the trigger_gridly() function?

Upvotes: 1

Views: 91

Answers (3)

Eric Turner
Eric Turner

Reputation: 1824

As others have indicated, getJSON is an asynchronous call. You have to wait for it to invoke your callback before channel will be available. Here is how I might code it up:

function trigger_gridly() {
   get_channel_name(function(channel){
      var channel_name = channel.name;
      // Do something with channel_name
   });
}

function get_channel_name(success) {
   $.getJSON(APPLICATION_DOMAIN + "channels/new.json?callback=?", null, success); 
}

EDIT: An alternative that I like slightly better:

function trigger_gridly(channel) {
   var channel_name = channel.name;
   // Do something with channel_name
}

function get_channel_name(success) {
   $.getJSON(APPLICATION_DOMAIN + "channels/new.json?callback=?", null, success);
}

get_channel_name(trigger_gridly);

Upvotes: 1

saarp
saarp

Reputation: 1951

You need to declare channel_name outside the function scope. However, I am not sure this will get you what you want. This is set up for an async request/response. You want to perform your actions that use the channel name in the handleJson() function.

Like this:

var CHANNEL_NAME;

function trigger_gridly(){
    get_channel_name();
}

function get_channel_name(){
    $.getJSON(APPLICATION_DOMAIN + "channels/new.json?callback=?", null, handleJson);
}

function handleJson(channel){
    CHANNEL_NAME = channel.name;
}

Upvotes: 0

greut
greut

Reputation: 4363

it's quite ugly, but this will work, asynchronous processes are always a bit tricky getJSON is async.

function get_channel_name(fn) {
    $.getJSON(APPLICATION_DOMAIN + "channels/new.json?callback=?", null, function(channel) {
        fn(channel.name);
    });
}

var channel_name;
get_channel_name(function(name) {
    channel_name = name;
});
// but here channel_name is still undefined

Upvotes: 0

Related Questions