4

I have defined a class and I am trying to fetch a HTML file using XMLHttpRequest and assign the response to the variable in class but it won't change.

function UIHandler(){
    this.notificatoin = 0;
    this.msgBoxMe = 1;
    this.msgBoxThem = 2;
    this.getMsgBox(1);
    this.getMsgBox(2);
}

UIHandler.prototype.getMsgBox = function(me){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){//here we have the template in xhr.responseText
            this.msgBoxMe = xhr.responseText;
        }
    };
    switch(me){
        case 1:
            xhr.open("GET" , "chat/views/me.html" , true);
            break;
        case 2:
            xhr.open("GET" , "chat/views/them.html" , true);
            break;
    }
    xhr.send();
};

I assign the response in the onreadystatechange event handler to the this.msgBoxMe variable but it still has the value 1.

2
  • 2
    You realize it's asynchronous ? Commented Jul 12, 2014 at 10:11
  • Side note: JavaScript doesn’t have classes, see Prototype-based programming. Commented Jul 12, 2014 at 10:18

1 Answer 1

6

The this variable in your callback xhr.onreadystatechange doesn't point to the object.

A workaround is to define an additional variable (instance in the following example) that holds the object:

function UIHandler() {
    this.notificatoin = 0;
    this.msgBoxMe = 1;
    this.msgBoxThem = 2;
    this.getMsgBox(1);
    this.getMsgBox(2);
}

UIHandler.prototype.getMsgBox = function(me){
    var instance = this;   // points to object

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
         if(xhr.readyState == 4){ //here we have the template in xhr.responseText
              instance.msgBoxMe = xhr.responseText;
         }
    };
    switch(me){
         case 1:
              xhr.open("GET" , "chat/views/me.html" , true);
              break;
         case 2:
              xhr.open("GET" , "chat/views/them.html" , true);
              break;
    }
    xhr.send();
};
Sign up to request clarification or add additional context in comments.

3 Comments

thanks. i appreciate it very much. works like a charm!
but what does this refer to then?
@SNt Javascript scopes are a messy thing in my mind. It depends on the individual callback where this points to. I don't know what it is in this case. But debugging or console.log(this); will give you a hint.

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.