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?

Makis
  • 1,214
  • 3
  • 16
  • 40

2 Answers2

2

That be a job for a closure

$('#Form').submit( function (event) { save(event, parameter); });
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Ok, it worked like a charm. Can you please explain to me the reason that needs a closure. I'm new in Js! – Makis May 21 '15 at 17:01
  • 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 http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – epascarello May 21 '15 at 17:02
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".

Andreas
  • 1,997
  • 21
  • 35