...

View Full Version : XMLHttpRequest onreadystatechange in an object



Urmell
08-14-2008, 09:37 AM
Hello everyone,

I'm new to javascript so I'm trying all kinds of stuff to get a hang of it. I'm used to OOP so that's what I'm trying to do in javascript. It's been going well but now I got stuck at some point. Here's the object I made:

function objTest() {

this.intSomeVar = null;
this.ajaxRequest = null;

this.setTheVar = function(intValue) {
this.intSomeVar = intValue;
}

this.getTheVar = function() {
return this.intSomeVar;
}

this.doubleTheVar = function(intValue) {
var intTemp = this.getTheVar();
intTemp = intTemp * 2;
this.setTheVar(intTemp);
}

this.getVarFromFile = function() {
this.ajaxRequest = GetXmlHttpObject(); //<- some function thats creates the XMLHttpRequest object, it works

this.ajaxRequest.onreadystatechange = function() {
if(this.ajaxRequest.readyState == 4){ //<- not working :(
this.setTheVar(this.ajaxRequest.responseText);
}
}

this.ajaxRequest.open("GET", "somevar.txt", true);
this.ajaxRequest.send(null);
}
}
The function in bold is the one that doesn't work right. Now, I guess the problem is that I'm "creating" that callback function in there, so it's not part of the object, therefore I cant use any methods or properties in the object. How should I go about doing this?

Thanks in advance!

Arty Effem
08-14-2008, 10:52 AM
I can't test this but I think it's right:
this.getVarFromFile = function()
{
if( (this.ajaxRequest = GetXmlHttpObject()) ) //assuming it returns null on failure
{
this.ajaxRequest.onreadystatechange = (function(obj)
{
return function()
{
if(obj.ajaxRequest.readyState == 4)
obj.setTheVar(obj.ajaxRequest.responseText);
}
})(this);
}
}

You're welcome in advance.

Urmell
08-14-2008, 11:13 AM
Now there's something I'd never be able to figure out myself :p It works, thanks alot!

SSJ
08-14-2008, 01:38 PM
What you exactly want to achieve by this code?

Urmell
08-14-2008, 09:19 PM
What you exactly want to achieve by this code?
Basically.. knowledge of javascript :p I know the whole code is useless, I just wrote it to test creating an object, using variables in an object, calling methods in an object (and from within an object), assigning values to a variable with a method etc. Just my method of learning a new programming/scripting language; doing rather than just reading. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum