YakovL
YakovL

Reputation: 8365

Is xhr always available inside onreadystatechange as a property of the argument? Which one to use?

My goal is to make a couple of XHR onreadystatechange handlers self-contained meaning that I'd like to get the XHR object inside them without using a closure (so I'm able to stack them in any order). Here's the main part of the code:

var xmlhttp;
function receiveOriginal()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        ...
    }
}
...
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = receiveOriginal;
xmlhttp.open("GET", url, true);
xmlhttp.send();

Now, I'd like to make it like

function receiveOriginal()
{
    xmlhttpInside = ... // get it any way without using a closure
    if (xmlhttpInside.readyState == 4 && xmlhttpInside.status == 200)
    {
        ...
    }
}
...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = receiveOriginal;
xmlhttp.open("GET", url, true);
xmlhttp.send();

I've found out that this actually works (at least in Vivaldi and Chrome):

function receiveOriginal(ev)
{
    xmlhttpInside = ev.currentTarget;
    // or
    xmlhttpInside = ev.srcElement;
    // or
    xmlhttpInside = ev.target;
    // each of these return true: xmlhttp === ev.currentTarget , xmlhttp === ev.srcElement , xmlhttp === ev.target
    if (xmlhttpInside.readyState == 4 && xmlhttpInside.status == 200)
    {
        ...
    }
}
...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = receiveOriginal;
xmlhttp.open("GET", url, true);
xmlhttp.send();

But the problem is, I'm looking throught a tutorial after tutorial and all of them, even the W3C reference (this is the final one, right?), all of them say nothing about the argument passed to a onreadystatechange handler. So I have no idea:

Upvotes: 0

Views: 163

Answers (1)

Rob M.
Rob M.

Reputation: 36521

target, currentTarget, and srcElement are all properties of the native Event object (documentation), which onreadystatechange receives (because it is an event handler). There are many ways to handle this - all of which are perfectly fine. I personally prefer to use this for the onreadystatechange callback:

function receiveOriginal() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText)
    }
}

Upvotes: 1

Related Questions