I’m using XMLHttpRequest, and I want to access a local variable in the success callback function.
Here is the code:
function getFileContents(filePath, callbackFn) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callbackFn(xhr.responseText);
}
}
xhr.open("GET", chrome.extension.getURL(filePath), true);
xhr.send();
}
And I want to call it like this:
var test = "lol";
getFileContents("hello.js", function(data) {
alert(test);
});
Here, test would be out of the scope of the callback function, since only the enclosing function’s variables are accessible inside the callback function. What is the best way to pass test to the callback function so the alert(test); will display test correctly?
Edit:
Now, if I have the following code calling the function defined above:
for (var test in testers) {
getFileContents("hello.js", function(data) {
alert(test);
});
}
The alert(test); code only prints the last value of test from the for loop. How do I make it so that it prints the value of test during the time at which the function getFileContents was called? (I would like to do this without changing getFileContents because it’s a very general helper function and I don’t want to make it specific by passing a specific variable like test to it.
With the code you have provided
testwill still be in scope inside the callback.xhrwill not be, other thanxhr.responseTextbeing passed in asdata.Updated from comment:
Assuming your code looks something like this:
As this script runs,
testwill be assigned the values of the keys intesters–getFileContentsis called each time, which starts a request in the background. As the request finishes, it calls the callback.testis going to contain the FINAL VALUE from the loop, as that loop has already finished executing.There is a technique you can use called a closure that will fix this sort of problem. You can create a function that returns your callback function, creating a new scope you can hold onto your variables with:
This will basically create a new scope (along with our new function) that will “hold on” to the value of
test.Another way of writing the same sort of thing: