Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's AJAX call to a javascript class method

I'm a newbee about jQuery's workflow and I would like to setup a javascript class that uses an internal method to make an AJAX request. When the request returns with success, the jQuery AJAX callback should invoke a method owned by the class itself. That's the code:

function IXClock()
{
    this.m_intervalID = 0;

    this.startClock = function ()
    {
        this.m_intervalID = setInterval(this.tictac, 500);
    }

    this.stopClock = function ()
    {
        clearInterval(this.m_intervalID);
    }

    this.setClockTime = function(p_strTime)
    {
        $('#clock').html(p_strTime);
    }

    this.tictac = function ()
    {
        $.ajax
        ({
                type: 'POST',
                url: '/rap/rapClock.php',
                complete: function (data)
                {
                    this.setClockTime(data);
                }
        });
    }

}

The class represents a clock, with an internal method (tictac) that requests "what's the time" on the server side. After the server says the time, the jQuery's AJAX method should invoke the setClockTime method of the IXClock class. The invoke method will update the #clock div item in the html page.

The problem is that the method this.setClockTime() results unknown and the javascript return the "this.setClockTime is not a function" error.

The question is: is there a way to invoka a class method from the jQuery's AJAX callback ?

like image 380
iakko Avatar asked Sep 14 '10 10:09

iakko


1 Answers

I think that the problem is that the this in your callback function is different from the this referring to IXClock. Try:

var thisClass = this ;
this.tictac = function ()
{
    $.ajax
    ({
            type: 'POST',
            url: '/rap/rapClock.php',
            complete: function (data)
            {
                thisClass.setClockTime(data);
            }
    });
}

Test Case (added to site which already has jQuery loaded):

function uClass () {
    this.testFunction = function(input) {
        alert(input) ;
    }
    this.ajaxFunction = function() {
        var myClass = this ;
        $.ajax({
            type: 'POST',
            url: '/',
            complete: function(data) {
                alert(myClass.testFunction) ;
                myClass.testFunction(data) ;
                this.testFunction(data) ;
            }
        }) ;
    }
}

var k = new uClass() ;
k.ajaxFunction() ;
like image 172
Gus Avatar answered Sep 22 '22 05:09

Gus