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?
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.
-
Try this :
xhr.onload = this.methodThree;
-
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?
-
Cheers that's the one :)