Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outer scope in JavaScript

So I've got this JS code here, and I'm trying to set obj from the success and error callbacks, but apparently the toLinkInfo function scope is not a parent scope of those? I always get null back from this function no matter what. I tried a bunch of stuff but couldn't get it to work, I guess I'm too used to C & friends :) How can I get this to work?

LinkInfoGrabber.prototype.toLinkInfo = function() {
    var obj = null;
    $.ajax({
        url: this.getRequestUrl(),
        success: function(raw) {
            obj = new LinkInfo(raw);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            obj = new LinkInfoException(jqXHR, textStatus, errorThrown);
        },
        dataType: 'html'
    });

    if (obj instanceof LinkInfo) {
        return obj;
    } else {
        throw obj;
    }
}
like image 521
Jake Petroules Avatar asked Jul 13 '11 03:07

Jake Petroules


1 Answers

That's because AJAX calls are asynchronous -- they happen at a different time from the rest of the context.

Try giving it a callback function( called callback below ).

LinkInfoGrabber.prototype.toLinkInfo = function(callback) {
    $.ajax({
        url: this.getRequestUrl(),
        success: function(raw) {
            callback( new LinkInfo(raw) );
        },
        error: function(jqXHR, textStatus, errorThrown) {
            obj = new LinkInfoException(jqXHR, textStatus, errorThrown);
        },
        dataType: 'html'
    });
}

var l = new LinkInfoGrabber()
l.toLinkInfo(console.log) //replace console.log with something meaningful

While this approach does not provide exactly the same result as being able to call everything inline, it has the benefit of allowing for the asynchronous nature of the web.

like image 88
cwallenpoole Avatar answered Oct 02 '22 22:10

cwallenpoole