This is a very common doubt in Javascript.
How to make the hidden function Groups() be assigned to my
element without it being executed at the time of assignment? Has as
solve this problem?
Understanding the problem
First, you have to understand why your function is executed at the time of assignment. Let’s go to a simpler example:
function soma(x, y) {
return x + y;
}
soma(5, soma(3, 2));
When you read the code above, you surely understand that you are not passing the function soma
as a parameter for itself, and yes the result of the execution from within. Then, you would read the code above as soma(5, soma(3, 2)) = soma(5, 5) = 10
.
I mean, when you’re doing elemento.click(escondeProdutosGrupo(g,elemento));
, you are calling the function hidesProducts Group with these parameters in specific, and the result of this function (which in the case is probably a void), you are passing as parameter to the function click
jQuery.
There are some ways to resolve this situation:
Option 1: Anonymous function
The most common and simple is you encapsulate the code to be executed in an anonymous function:
elemento.click(function() {
escondeProdutosGrupo(g, elemento);
});
In that case, you’re moving on to the event click
a function that will be executed, and this function will call the escondeProdutosGrupo
as you expect it to happen.
Option 2: Function.prototype.bind
From ES5, you have the option to use the method bind
which exists in all instances of language function. You pass as the first parameter to this method what you would like it to be the this
within that method (pass null
if you do not want to change the scope, or if this is not important to your question). And the other parameters will be the parameters that will be passed to the call of that function.
elemento.click(escondeProdutosGrupo.bind(null, g, elemento));
This way, you are passing as parameter the function itself, already loaded with its future parameters, which will be executed when the event click
occur.
Pass like callback, like this:
elemento.click(mostraProdutosGrupo);
, without making the call.– Fernando Leal
and the parameters... how they look
– Paulo Roberto Rosa
can for an example in jsFiddle, with the html element code that delegates the first event?
– Fernando Leal
From what I understand you want
bindar
an event to the object and at the same timeguardar
some parameters to be used later, that’s it?– Cahe
That @Cahe exactly
– Paulo Roberto Rosa
Read about the function bind.
– user21448
You can give an example of your HTML and how you are calling the function
mostraProdutosGrupo
?– Sergio
This is no satisfactory answer since 2014? Just put
function(){mostraProdutosGrupo(g,elemento)}
in place ofmostraProtudosGrupo(g,elemento)
. I’ve already welcomed the answer that goes straight to the point, the Rubico, but I’m commenting because it can be hidden among the others.– marcus