user656925
user656925

Reputation:

Retrieving callback value from calling function. How to?

In a function I make an ajax call, the call back has the response_text I need in that function. I tried the obvious of putting a var here in the calling function and using it in the callback function. This does not work. Next I tried using a function out() which is how I've done this before. This works as I can now access response_text from out(). However, is there a way to access from vOrb() directly, that is, the original calling function?

I don't want to place all the code in the call back as in this SO Question

Would the module pattern work as a way to keep var here in scope when the callback function make its asynchronous return? Or would simply writing var vOrb = function(){} as a wrap and call using new, do the trick?

function vOrb( icon_array )
{
    var here; // does not work
    function out( here ){} // does work
    new AjaxRequest().invoke( 'ajax_type=fav_dir', function( response_text )
    {
        out( response_text );
    } ); 

// want response_text here

Upvotes: 0

Views: 87

Answers (1)

Denis
Denis

Reputation: 1093

I’m not sure if I understood everything right but I’ll try to answer anyway. If this is what you want, you can't use response_text outside your callback - it would be undefined.

It’d be better to proceed like so :

function vOrb( icon_array )
{
    new AjaxRequest().invoke( 'ajax_type=fav_dir', myCallback ); 
    var myCallback = function ( response_text ) {
        // blah…
    };
}

If you absolutely want to use response_text outside your callback, then you'll have to check if it is set first.

var my_response;
function vOrb( icon_array )
{
    new AjaxRequest().invoke( 'ajax_type=fav_dir', myCallback ); 
    var myCallback = function ( response_text ) {
        my_response = response_text;
    };
}

// ...

if ( typeof my_response !== 'undefined' ) { // will only work after the callback is triggered
    // use "my_response" here
}

Upvotes: 1

Related Questions