Is there any difference between an event with passing parameters to one without passing?

Asked

Viewed 73 times

5

Considering:

jQuery

$("#seletor1").on("click", function(){
    $("#seletor2").trigger("click", {dados: "informação"});
});
$("#seletor2").on("click", function(){
    //faça coisas
});
$("#seletor2").on("click", function(evento, dados){
    //faça coisas
});

Which one will it trigger?

1 answer

6


Both will be triggered. The passage of the parameters is determined by who issues the event, not by their appointment in the listeners. Therefore the first parameter (event object) is always passed by jQuery, regardless of whether it is named in your System or not.

In the first case, evento and dados can still be accessed via arguments[0] and arguments[1] respectively:

$("#seletor2").on("click", function(){
    var evento = arguments[0];
    var dados = arguments[1];
});

In your second Systener, the variables do not need to be defined because the parameters are already named, but the object arguments is also available:

$("#seletor2").on("click", function(evento, dados){
    console.log(evento === arguments[0]); // true
    console.log(dados === arguments[1]); // true
});
  • Could give some example of coding using arguments[x] or would that go beyond the scope of the question? I gave a search for the internet and found nothing very relevant.

  • I reorganized the answer and put an example, see if it was clearer. It’s in the scope of the yes question.

  • So Arguments is like an array of arguments? I mean, can I use directly arguments[x]?

  • 1

    That’s right. The arguments have numerical indexes and the total quantity can be obtained in arguments.length. But it is not a real array, it is a "disguised object".

  • In the code example in the question, an object is being passed as parameter; the way to get the "information" value of that object would be arguments[1].dados?

  • 1

    IS, arguments[1].dados, or dados.dados in the second example. Moreover, it is preferable to use named arguments where possible.

Show 1 more comment

Browser other questions tagged

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