Access to external area in JavaScript

So, I have this JS code here, and I'm trying to install obj from successful and error callbacks, but apparently the scope of the possibilities is toLinkInfonot the parent scope? I always come back from this function no matter what. I tried a bunch of things, but couldn't get it to work, I think I'm too used to C and 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;
    }
}
+5
source share
3 answers

This is because AJAX calls are asynchronous - they occur at a different time from the rest of the context.

Try giving it a callback function (called a 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

, , .

+3

:

if (obj instanceof LinkInfo) {
        return obj;
    } else {
        throw obj;
    }

, ajax, obj , ajax . . Ajax- . $.ajax() , . , ajax ( ). obj . obj , , .

+3

obj , ajax, , null, .

0

All Articles