0
var mapFile = new XMLHttpRequest();
mapFile.open("GET", "http://localhost:8000/res/map01.txt", true);

mapFile.onreadystatechange = function() {
  if (mapFile.readyState === 4) {
    if (mapFile.status === 200) {
      this.lines = mapFile.responseText.split("\n");
    }
  }
}

this.lines = mapFile.onreadystatechange.lines;

mapFile.send(null);

I have that code and I'm trying to save this.lines inside mapFile.onreadstatechange to later save as this.lines on the outer scope. However, mapFile.onreadystatachange.lines is undefined and I can't save the variable for later use. I even tried using element.innerHTML which is a dirty hack for this but it also didn't work.

2
  • JS has function-scope. So your this within the onreadystatechange callback is different from the one outside. Pass the outside this into it. Commented Feb 2, 2013 at 11:54
  • I tried to do var outsideScope = this; outside and then try to access outsideScope on the inside but it didn't work. Is that what you mean? Commented Feb 2, 2013 at 12:02

1 Answer 1

2

There are three primary issues here:

  1. The this within onreadystatechange is not the same as the this outside of the function, because this within a function is determined by how the function is called. More on my blog: Mythical methods | You must remember this

  2. XHR calls are asynchronous (by default), so your callback won't have been called yet when you're trying to use this.lines just above the send call. (Even with a synchronous request, since that line is before send, it still wouldn't be set.)

  3. mapFile.onreadystatechange.lines looks for a property called lines on the function object referenced by mapFile.onreadystatechange. It has absolutely nothing to do with any variables defined within that function.

Here's an update addressing the main items:

var mapFile = new XMLHttpRequest();
var self = this; // <===== Remember `this` for use in the callback
mapFile.open("GET", "http://localhost:8000/res/map01.txt", true);

mapFile.onreadystatechange = function() {
  if (mapFile.readyState === 4) {
    if (mapFile.status === 200) {
      // v---- Use self instead of this
      self.lines = mapFile.responseText.split("\n");
    }
  }
}; // <=== Add missing semicolon

// Removed a line here using `this.lines` prematurely

mapFile.send(null);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.