This is a very common question in Javascript.
How to make the function hideGroups () be assigned to my
without being executed at the time of allocation? Has as
to solve this problem?
Understanding the problem
First, you have to understand why your function should be run at the time of assignment. Let's take a simpler example:
function soma(x, y) {
return x + y;
}
soma(5, soma(3, 2));
When you read the code above, you certainly understand that you are not passing the soma
function as a parameter to itself, but rather the result of execution from within. So, you would read the above code as soma(5, soma(3, 2)) = soma(5, 5) = 10
.
That is, when you are doing elemento.click(escondeProdutosGrupo(g,elemento));
, you are calling the hideProductsGroup function with these parameters in specific, and the result of this function (which in this case is probably a void), you are passing as parameter to the% jQuery click
.
There are a few ways to resolve this:
Option 1: Anonymous function
The most common and simple is to encapsulate the code to be executed in an anonymous function:
elemento.click(function() {
escondeProdutosGrupo(g, elemento);
});
In this case, you are passing to the click
event a function that will be executed, and this function will call escondeProdutosGrupo
as you expect it to happen.
Option 2: Function.prototype.bind
Starting in ES5, you have the option to use the bind
method that exists in all language function instances. You pass as the first parameter to this method what you would like to be this
within that method (pass null
if you do not want to change the scope, or if that is not important for 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));
In this way, you are passing as parameter the function itself, already loaded with your future parameters, which will be executed when the click
event occurs.