Why doesn't Ajax use self-invocation?

298 views Asked by At

The weird syntax of a self-invoking closure function implies that you are essentially calling the function itself, hence making it self-invoking. Here is some code demonstrating this:

<!DOCTYPE html>
<html>
    <head>
        <title>
            A Nameless Function that Executes Itself
        </title>
    </head>

    <body onload = "mainMethod();">

        <div id = "here"></div>

        <script type = "text/javascript">

            function mainMethod()
            {
                var here = document.getElementById("here");
                var hello = "Hello World!";

                here.innerHTML = function()
                {
                    return hello + "<br />";
                }(); // WITH method parentheses -- self-invoking

                here.innerHTML += function()
                {
                    return hello;
                }; // withOUT method parentheses
            }
        </script>
    </body>
</html>


...the second function above does not execute because it lacks the ending parentheses, and the innerHTML becomes the entire function itself. So, why doesn't your standard Ajax syntax use self-invocation in the same way? It would seem that the XMLHttpRequest processes the onreadystatechange attribute in a unique way. Here is an example:

function getStock()
{
    var req = new XMLHttpRequest();

    var stock = document.getElementById("stock");

    req.onreadystatechange = function()
    {
        if( (req.readyState == 4) && (req.status == 200) )
        {
            // value of stock
            var stockValue = req.responseText;

            stock.innerHTML = stockValue;
        }
    }
    req.open("GET", "randomStockValue.php?random=", true);
    req.send(null);

    setTimeout("getStock()", 1000);
}


Notice the lack of ending parentheses... I'm asking this because I want to further understand Ajax syntax, and what exactly it is doing.

3

There are 3 answers

2
Bergi On BEST ANSWER

It registers an event listener. The function does not get executed instantly, it (the Function object) is just assigned to the onreadystatechange property. It will be invoked some later time - when the ajax request changes its state. It's something like a setTimeout with an unknown timeout (and it will be invoked more than one time).

0
jfriend00 On

The readystatechange property holds a callback function (or sometimes called an event handler function) that will be called by the ajax engine of the browser multiple times in the future when certain ajax events occur.

You do not want it to execute immediately. You want the function you assign to it to be called in the future when those certain events occur. You do not want it to be self-executing.

For other examples of event listeners or callback functions that are called some time in the future, see methods like addEventListener() or setTimeout().

0
mpm On

There is nothing special with the ajax call handler , you can write the exact same code for the first exemple and it will perform the same wait :

      function mainMethod()
            {
                var here = document.getElementById("here");
                var hello = "Hello World!";

                here.innerHTML = function()
                {
                    return hello + "<br />";
                }(); // WITH method parentheses -- self-invoking

                here.innerHTML += function()
                {
                    return hello;
                }; // withOUT method parentheses
            }

document.body.onload = mainmethod ;

you a giving 2 exemples that doesnt share the same context , that's why indeed they behave differently.

now try

document.body.onclick = mainmethod ;

and your fonction will not execute until you click on the webpage. Same thing for ajax call.