views:

55

answers:

2

Hi

I wanted to my code a bit cleaner so I wanted to put a very long function in it's own method.

Right now I have

$('#Id').submit(function()
{
   // lots of code here
});

now I wanted to break it up like

   $('#Id').submit(MyFunction);


        function MyFunction()
        {
           // code now here.
        }

but I need to pass in some parms into MyFunction. So I tried

$('#Id').submit(MyFunction(param1, param2));

function MyFunction(param1, param2)
{
   // code now here.
}

But when I do this nothing works. Firebug shows me some huge ass error about F not being defined or something. So I am not sure what I need to do to make it work.

+3  A: 

You just need to write:

$('#Id').submit(function()
{
   MyFunction(param1, param2);
});
Noon Silk
Thanks that seems to have done the trick. Any reason why you can't pass it in right away?
chobo2
Well, what you're doing there is setting up an anonymous function. I think you could pass it in right away (as your second example does), but when you need more params (from the context of the writing of that code, not the calling of the method) then you need to pass them through like that (because you aren't in charge of the .submit call, which actually calls you.
Noon Silk
@chobo2: Because there's no magic. If you write `foo.submit( MyFunction(one, two) )` then you are *calling* `MyFunction` right then and there, and (assuming that doesn't crash in the first place) attempting to pass its return value to `submit`.
hobbs
+1  A: 

You could try

$('#Id').submit(function() { MyFunction(param1, param2); });

The reason your code didn't work is that you were calling MyFunction(param1, param2) and passing the result to the Jquery submit - and that's not what you intended.

Vinay Sajip