PDA

View Full Version : Passing variables (specific to the XMLHttp object)


aluminumpork
01-15-2006, 08:32 PM
Okay, this one is pretty specific to the XMLHttpRequest object. When setting up the object before you send, I do something like this:



function addDate(date){
createXMLHttpRequest();

xmlHttp.onreadystatechange = addDateStateChange;
xmlHttp.open("POST", "addDate.php?date=" + date);
xmlHttp.send(null);
}



So that's straight-forward and all. The part I'm wondering about is the "onreadystatechange". I set that the function I want to use when the XMLHttp state changes, but I how can I pass a variable to it that is not global? I can't put "addDateStateChange(date);" on the end of it, that's no good. Right now I have to just var out a bunch a globals and use those, and I feel dirty for it :-D. Any ideas?

Thanks

RysChwith
01-16-2006, 09:15 AM
You could add a property to the request object and use that in the function:function addDate(date){
createXMLHttpRequest();

xmlHttp.dateVar = new Date();
xmlHttp.onreadystatechange = addDateStateChange;
xmlHttp.open("POST", "addDate.php?date=" + date);
xmlHttp.send(null);
}That's about the best I can come up with, although it seems like there should be a more streamlined way.

Rys

Jon Hanlon
01-16-2006, 05:06 PM
What you need is a closure (http://en.wikipedia.org/wiki/Closure_%28computer_science%29)!
Javascript is a perfect language for generating closures, which are functions that encapsulate their own set of variables.

function closureDate(inDate) {
function addDateStateChange() {
var oTarget = inDate; // we now have a local reference of the date
// normal code goes here...
}
return addDateStateChange; /* return a reference to the inner function defined above */
}

xmlHttp.onreadystatechange = closureDate(date);


In a nutshell what happens is that the script evaluates closureDate(date), which results in a function object. This object has had to evaluate 'date' on the way through, and leaves a local copy of it in the variable oTarget.

aluminumpork
01-16-2006, 07:28 PM
Thanks for the great replies! I'll have to check into this. Thanks again!

RysChwith
01-17-2006, 09:30 AM
Your script fu is better than mine, Jon. I could never wrap my head around closures, somehow.

Rys