Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $.getJSON() with callback within a Javascript object

I'm trying to set up an object so that it has an encapsulated $.getJSON method. Here's my setup:

function Property(price, deposit){
  this.price = price;
  this.deposit = deposit;
  this.getMortgageData = function(){
    $.getJSON('http://example.com/index?p='+this.price+'&d='+this.deposit+'&c=?', function(data){
        this.mortgageData = data;
    });
  }
  return true;
}

Now the problem seems to be that I don't have access to 'this' inside the getJSON callback function which makes sense.

Is there a workaround for this type of function or am I just thinking about this totally the wrong way? I've only ever really coded using PHP OO before so JS OO is a bit new to me.

Other things I've tried are:

  function Property(price, deposit){
  this.price = price;
  this.deposit = deposit;
  this.getMortgageData = function(){
    this.mortgageData = $.getJSON('http://example.com/index?p='+this.price+'&d='+this.deposit+'&c=?', function(data){
        return data;
    });
  }
  return true;
}

But still,

var prop = new Property();
prop.getMortgageData();
// wait for the response, then
alert(prop.mortgageData.xyz); // == undefined
like image 390
David Tuite Avatar asked Jan 27 '11 15:01

David Tuite


1 Answers

Your first attempt is close, but as you said, you can't access this inside the callback because it refers to something else. Instead, assign this to another name in the outer scope, and access that. The callback is a closure and will have access to that variable in the outer scope:

function Property(price, deposit){
  this.price = price;
  this.deposit = deposit;
  var property = this; // this variable will be accessible in the callback, but still refers to the right object.
  this.getMortgageData = function(){
    $.getJSON('http://example.com/index?p='+this.price+'&d='+this.deposit+'&c=?', function(data){
        property.mortgageData = data;
    });
  }
  return true;
}
like image 160
kevingessner Avatar answered Sep 27 '22 15:09

kevingessner