Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

JS Obj Help

So I have and object and have defined some methods like:

function MyObj(){
  this.methodOne = function(){
    //Do something
  }
  this.methodTwo = function(){
    //Do something else
  }
}

In methodTwo I have to call for some data via XHR however the onload method requires me to create a function which gets executed when data is returned. I want to call methodOne after the data is loaded. However if I try to call that method via this.methodOne it doesn't work since this is treated at the XHR object rather than my own object. So this is what I have:

function MyObj(){
  this.methodOne = function(){
    //Do something
  }
  this.methodTwo = function(){
    ...
    xhr.onload = function(){
      this.methodOne();
    };
    ...
  }
}

I've tried declaring a method in my object which gets run on data load however then I loose the responseData. e.g.

function MyObj(){
  this.methodOne = function(){
    //Do something
  }
  this.methodTwo = function(){
    ...
    xhr.onload = this.methodThree();
    ...
  }
  this.methodThree = function(){
    //Can't access responseData in here.
  }
}

Any ideas how I can do this?

— asked May 1st 2010 by Jordan de Laune
  • javascript
  • objects
  • xhr.onload
0 Comments

4 Answers

  • Accepted Answer

    This is a common gotcha in JS. Define another local variable like

    var that = this;

    And capture that in a closure in order to retain a reference to your object. See the book 'JavaScript - the good parts' for a better explanation.

    — answered May 1st 2010 by Damien Elmes
    permalink
    0 Comments
  • Try this :

    xhr.onload = this.methodThree;

    — answered May 1st 2010 by Joel Bohrer
    permalink
    0 Comments
  • Great so I can access the responseData but it overrides my object instance so if I try to call this.methodOne(); from within methodThree(); it won't find it because this references the xhr object.

    Any clues?

    — answered May 1st 2010 by Jordan de Laune
    permalink
    0 Comments
  • Cheers that's the one :)

    — answered May 2nd 2010 by Jordan de Laune
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.