How does a function run automatically without being called?

Asked

Viewed 6,487 times

7

I can create a Javascript function and call it as follows:

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

funcaoTeste();

To perform the function I need to call her funcaoTeste(), however, sometimes I come across Javascript codes in which a function runs but I don’t see where it’s called.

See this practical 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 functions onload() and onsubmit() have been declared, but there is no call for them in the script. It seems that this occurs in an automatic way that I do not know.

Questions

  1. How a function is executed automatically without being called?
  2. Who is responsible for carrying out the tasks onload() and onsubmit()?
  • Are performed at events load and submit respectively.

1 answer

5


The engine browser will do this. It is the one who controls all execution and calls some events.

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

The same occurs with the onsubmit which is an event to be called every time you start the form submission.

The event system is very useful throughout the system where you want to control the execution, but give some hooks (Hooks) for the user of this system, in this case the programmer of the script can customize some specific action when something happens.

Deep down it’s a callback.

Behold What is Event-Oriented Programming?. I do not consider JS alone oriented to events, but the whole engine is.

How it works in C#.

In the background events apply the Observer design standard. As can be seen in Design Observer applied to events.

It is also useful to understand what is inversion of control which is what happens with the engine JS, most Guis and other applications like framework.

  • This only happens with events, right?

  • 1

    Occurs with callbacks in general. I’m not so into the JS to state this, but I think that all the callbacks JS standards in browsers are events.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.