How does a function run automatically without being called?

6

I can create a function in JavaScript and call it as follows:

funcaoTeste = function() 
{
	console.log('Ola funcao teste');
};

funcaoTeste();

To execute the function I need to call it funcaoTeste() , entertaining, sometimes I run into JavaScript codes where a function is executed but I do not see where it is called.

See this handy illustration example:

window.onload = function()
{
    document.getElementById('form-exemplo').onsubmit = function (event) 
    {
        if ( CPF.validate(document.getElementById('cpf').value) !== true ) 
        {
            alert("CPF invalido");
            return false;
        }
    };
};

The code above refers to this form:

<form method="post" id="form-exemplo">
    <label for="nome">Nome </label>
    <input type="text" id="nome" placeholder="Digite o nome" required>

    <label for="cep">CEP </label>       
    <input type="text" id="cep" placeholder="Digite o CEP" required pattern="\d{5}-?\d{3}">

    <label for="cpf">CPF </label>
    <input type="text" id="cpf" placeholder="Digite o CPF" required>

    <input type="submit" value="Enviar">
</form>

Note that the onload() and onsubmit() functions have been declared, but there is no call to them in script . It seems that this occurs in an automatic way that I do not know.

Questions

  • How does a function run automatically without being called?
  • Who is responsible for performing the onload() and onsubmit() ?
  • asked by anonymous 01.04.2017 / 22:55

    1 answer

    4

    The engine browser will do this. It controls all execution and calls some events.

    The onload is an event, so when you play a function on it, when the page loads, the engine will call this function.

    The same thing happens with onsubmit which is an event to call every time you start submitting the form.

    The event system is very useful on every system where you want to either control the execution, but give a few hooks ( hooks ) so that the user of this system, in this case the script can customize some specific action when something happens.

    At the bottom is a callback .

    See What is Event-Oriented Programming? . (I do not consider JS alone event-driven, but the entire browser is).

    How it works in C # .

    In the background events apply the Observer project pattern . As can be seen in Design pattern Observer applied to events .

    It's also helpful to understand what control inversion is what happens with the engine JS, most GUIs and other applications like framework .

        
    01.04.2017 / 23:08