Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Referencing outer scope within callback

I have an issue with OO Javascript and a jQuery callback. If you look at the sample below it should explain everything.

How do I call functionToCall() deep within this functception.

function outerClass() {
    this.functionToCall = function() {
        //do something
    }

    this.someOtherFunction = function() {

    this.aCoupleOfVariables1 = 2;
    this.aCoupleOfVariables2 = "stuff";

    $.ajax({
        success: function() {
        //How do I call functionToCall() right here
        //TRIED:
            functionToCall();
            this.functionToCall();
            that.functionToCall();
        }
    }); 
    }
}
like image 753
SomeShinyObject Avatar asked Aug 09 '11 14:08

SomeShinyObject


3 Answers

You can pass this as the context option to $.ajax():

$.ajax({
    context: this,
    success: function() {
        // Here, 'this' refers to the same object as in the caller.
        this.functionToCall();  
    }
});
like image 139
Frédéric Hamidi Avatar answered Oct 05 '22 03:10

Frédéric Hamidi


Have a local reference to it,

function outerClass() {

    var self = this;

    this.functionToCall = function() {
    //do something
    }

    this.someOtherFunction = function() {

    this.aCoupleOfVariables1 = 2;
    this.aCoupleOfVariables2 = "stuff";

    $.ajax({
        success: function() {
           self.functionToCall();
       }
    }); 
   }
}
like image 38
Andrew Avatar answered Oct 05 '22 02:10

Andrew


You need to define that in the outer scope.

function outerClass() {
    var that = this;

    // ...

     $.ajax({
        success: function() {
            that.functionToCall();
        }
    }); 
}
like image 38
Matt Ball Avatar answered Oct 05 '22 04:10

Matt Ball