0

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

2 Answers 2

2

That be a job for a closure

$('#Form').submit( function (event) { save(event, parameter); });
answered May 21, 2015 at 16:58
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, it worked like a charm. Can you please explain to me the reason that needs a closure. I'm new in Js!
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/…
1

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".

answered May 21, 2015 at 17:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.