2

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

Vincent van der Weele
  • 12,927
  • 1
  • 33
  • 61
Ajouve
  • 9,735
  • 26
  • 90
  • 137

3 Answers3

5

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();
        }
    })
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
mikach
  • 2,427
  • 2
  • 14
  • 15
3

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();
        }
    })
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thanks this is a good answer but I prefer Michael's answer, I find this more proper – Ajouve Jul 26 '13 at 08:37
  • @ant Personally I really prefer to always keep in mind the native closure based solution than to try to remember all the parameters of the `ajax` function. But his answer is good too (I upvoted it) so I won't reproach you to choose it. Simply be sure to understand my answer because it's the solution you'll use in all other similar cases :) – Denys Séguret Jul 26 '13 at 08:39
  • 1
    @ant dystroy answer is more readable .. Michael's answer using `this` will make confusion – rab Jul 26 '13 at 08:42
0

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();
        }
    })
}
Ayman Farhat
  • 2,010
  • 3
  • 17
  • 16