3

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.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Saeed Entezari
  • 3,685
  • 2
  • 19
  • 40

1 Answers1

5

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();
};
Marcel Pfeiffer
  • 1,018
  • 11
  • 12