Events jQuery runs automatically

3

I have the following code:

    $(function(){
      function teste(teste){
        console.log(teste);
      }
      $('element').on('click', teste('teste'));
    })

When I run this code, the teste function is triggered without clicking the button, ie automatically.

And in the following code, everything works ok.

    $(function(){
      function teste(){
        console.log('teste');
      }
      $('element').on('click', teste);
    })

Why does not the first code work?

    
asked by anonymous 10.03.2014 / 12:45

1 answer

7

When declaring a function, a reference to it is created with its name.

See the following example, slightly modified to "unbind" the names:

function teste(param){
    console.log(param);
}
console.log(teste);

Note that teste is a reference to the declared function. However, the moment you use the parentheses to the right of the reference, you are directly requesting the function to execute:

teste('teste') //executa a função 

If your intention is to pass a reference and parameters at the same time, this is not possible. At least not that way.

A possibility to pass arbitrary parameters to a function used in% of jQuery% can be found in the on() parameter, as per documentation .

See the following example:

$(function(){
    function teste(param) {
        console.log(param.data.teste);
    }
    $('elemento').on('click', {teste: 'teste'}, teste);
});

By passing an object with the data q property in the second argument of the teste function of jQuery, we can access its value when the on function is executed through the teste attribute of the received parameter.

Demo on Jsfiddle

    
10.03.2014 / 12:59