-1

I have this code:

$(function(){
    $("#CASA").click(function(){
        rsExecute("rs/rs_luci.php","premi",1,function(cc){});
        var col=$( this ).css( "background-color" );
        setColor(this, 'yellow');
        setTimeout(setColor,1000,this,col);
    });
});

function setColor(obj,clr){
    $(obj).css( "background-color", clr );
}

rsExecute makes a call via ajax. function(cc){} is executed on success.

I've tried to change the code like this:

$(function(){
    $("#CASA").click(function(){
        rsExecute("rs/rs_luci.php","premi",1,function(cc){
            var col=$( this ).css( "background-color" );
            setColor(this, 'yellow');
            setTimeout(setColor,1000,this,col);
        });
    });
});

function setColor(obj,clr){
    $(obj).css( "background-color", clr );
}

but it doesn't work because this is undefined.

Is there a way to pass this object to the function inside rsExecute?

Atman
  • 35
  • 9

1 Answers1

-2

Save it to a variable, traditionally named 'that', and pass that variable using the closure.

$(function(){
    $("#CASA").click(function(){
        var that = this;
        rsExecute("rs/rs_luci.php","premi",1,function(cc){
            var col=$( that ).css( "background-color" );
            setColor(that, 'yellow');
            setTimeout(setColor,1000,that,col);
        });
    });
});
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29
  • 2
    This was the best approach more than a decade ago. Much better alternatives exist today: `(cc) => {`…`}` or `function(cc){`…`}.bind(this)`. But all of this is already suggested in the fourth most frequently linked JS question on Stack Overflow. – Sebastian Simon Nov 02 '21 at 22:49
  • Agreed, this was using the same conventions that the OP had in original snippet. – Jkarttunen Nov 03 '21 at 09:15