I want to achieve to pass a parameter to a function with an event handler.
What i'm trying to achieve is something like this
$('#Form').submit(save(parameter));
function save(event, parameter){
event.preventDefault();
}
In which way should i make it?
asked May 21, 2015 at 16:56
Makis
1,2643 gold badges17 silver badges45 bronze badges
2 Answers 2
That be a job for a closure
$('#Form').submit( function (event) { save(event, parameter); });
answered May 21, 2015 at 16:58
epascarello
208k20 gold badges206 silver badges246 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Makis
Ok, it worked like a charm. Can you please explain to me the reason that needs a closure. I'm new in Js!
epascarello
Because you need a reference to the function and your way, you were executing the function and assigning it to the submit event. Please look at stackoverflow.com/questions/111102/…
There are two ways to achieve this. The first one is a closure:
$('#Form').submit( function (event) { save(event, parameter); });
The second one is the bind-function:
$('#Form').submit(save.bind(null, parameter));
function save(parameter, event){
event.preventDefault();
}
Please note that you need to reorder the parameters of "save" here. The first parameter of the bind-function is the value for "this" inside the save-function. Here it is "null" which means "unchanged".
Comments
lang-js