quano
quano

Reputation: 19112

jQuery - get reference to this

function Request(params)
{
    // Stuff stuff stuff

    // And then

    $.ajax(
    {
        type: 'GET',
        url: 'someurl',
        success: this.done
    });
}

Request.prototype.done = function()
{
    // "this" in this context will not refer to the Request instance.
    // How to reach it?
}

Upvotes: 1

Views: 225

Answers (4)

Philippe Leybaert
Philippe Leybaert

Reputation: 171784

You could capture "this" first:

function Request(params)
{
    // Stuff stuff stuff

    // And then

    var $this = this;

    $.ajax(
    {
        type: 'GET',
        url: 'someurl',
        success: function() { $this.done(); }
    });
}

Upvotes: 4

quano
quano

Reputation: 19112

Apparently you can add the "context" parameter to the ajax request, like so:

$.ajax(
{
    type: 'GET',
    url: 'someurl',
    success: this.done,
    context: this
});

Upvotes: 3

rbhro
rbhro

Reputation: 208

try following:

function Request(params)
{
   var that = this;

....

Request.prototype.done = function()
{
   that...

Upvotes: -1

Thariama
Thariama

Reputation: 50832

this is not reffering to the same thing!!!

Upvotes: 0

Related Questions