Ajouve
Ajouve

Reputation: 10049

Javascript ajax and callback

I don't realy understand why my variable is undefined This is my code:

Calendar = function() {

    this.data;  
    this.init = function(path, callback){
        $.ajax({
            url:path,
            type:'GET',
            success:function(data){
                this.data = data;
                console.log(this.data);
                callback();
            }
        })
    }

    this.create = function(){
        this.generateYear();
    }   

    this.generateYear = function(){
        console.log(this.data); 
    }   
}

And I use it like this:

$(document).ready(function(){
    var calendar = new Calendar();
    calendar.init(path,function(){
        calendar.create();
    });
});

So the first console.log is good but the second is undefined, I don't understand why because he is called after.

Thanks for your help

Upvotes: 2

Views: 148

Answers (3)

Ayman Farhat
Ayman Farhat

Reputation: 2090

Within this.generateYear your call to "this" is not more referencing your Calendar object and is referencing the Window object which most probably doesn't have data as an attribute. Make sure you read more about Javascript binding

Storing an instance of this in a variable within your object and later using it, would work. Example:

this.init = function(path, callback){
    var self = this;
    $.ajax({
        url:path,
        type:'GET',
        success:function(data){
            self.data = data;
            console.log(self.data);
            callback();
        }
    })
}

Upvotes: 0

mikach
mikach

Reputation: 2427

Set context param in ajax function. Try this one:

 $.ajax({
        url:path,
        type:'GET',
        context: this,
        success:function(data){
            this.data = data;
            console.log(this.data);
            callback();
        }
    })

Upvotes: 5

Denys Séguret
Denys Séguret

Reputation: 382464

this, in the callback you give to ajax, isn't your calendar.

Change your init function to

this.init = function(path, callback){
    var calendar = this;
    $.ajax({
        url:path,
        type:'GET',
        success:function(data){
            calendar.data = data;
            console.log(calendar.data);
            callback();
        }
    })
}

Upvotes: 3

Related Questions