0

I am new to javascript and I would like to know how I can access my class variable inside my ajax callback

success: function(data) {
            var obj = jQuery.parseJSON(data);
            this.baralho = obj.countBaralho;

My Class

var Placar = {
    descarte : 0,
    jogador1: 0,
    jogador2: 0,
    baralho: 0,

    fetchFromServer: function(){
        $.ajax({
            url: baseUrl+'get-placar',
            success: function(data) {
                var obj = jQuery.parseJSON(data);
                this.baralho = obj.countBaralho;
                this.descarte = obj.countDescarte;
                this.jogador1 = obj.numCartas1;
                this.jogador2 = obj.numCartas2;
            }
        });

    },

    update: function() {
        $('#num-cartas-1').html(this.jogador1);
        $('#num-cartas-2').html(this.jogador2);
        $('#cartas-restantes').html(this.baralho);
        $('#num-cartas-descarte').html(this.descarte);
    }

}

The values aren't being setted from the server, How can I fix it?

1

1 Answer 1

2

The this in the ajax's success function is not your object(its probably an XMLHttpRequest object).

I would use a constructor to create the object instead of an object literal, and create a closure to be able to access the object in any context.

var Placar = new (function(){
    this.descarte = 0;
    this.jogador1 = 0;
    this.jogador2 = 0;
    this.baralho = 0;
            var self = this;        
    this.fetchFromServer = function(){
        $.ajax({
            url: baseUrl+'get-placar',
            success: function(data) {
                var obj = jQuery.parseJSON(data);
                self.baralho = obj.countBaralho;
                self.descarte = obj.countDescarte;
                self.jogador1 = obj.numCartas1;
                self.jogador2 = obj.numCartas2;
            }
        });

    };

    this.update = function() {
        $('#num-cartas-1').html(self.jogador1);
        $('#num-cartas-2').html(self.jogador2);
        $('#cartas-restantes').html(self.baralho);
        $('#num-cartas-descarte').html(self.descarte);
    };

})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.