Search code examples
javascriptangulartypescriptdatacontext

Get right context(this) in callback


I try to call a function in a callback and do something with the class context(this). But when calling the callback function, it doesn't have any context. this is undefined. I tried a few things with bind(self) but didn't work out.

export class AppComponent { 
    connect(call,callb){
            var self=this
            var xhttp = new XMLHttpRequest();
            xhttp.responseType=responseType
            xhttp.open("GET", "http://localhost:3000/"+call, true);
            xhttp.onreadystatechange = function(){
                if (xhttp.readyState == 4 && xhttp.status == 200)
                {
                    callb(xhttp.response).bind(self);                
                }
            };
            xhttp.send(null)
    }


    buildXML(response){
            console.log(this) //prints undefined, should print AppComponent or something
    }

    this.connect("someCall",this.buildXML)
}

Solution

  • You need to bind() the function context, then invoke it.

    callb.bind(self)(xhttp.response);
    

    instead of

    callb(xhttp.response).bind(self);