views:

95

answers:

1

Hi javascript developers,

Is there a way to reduce the boilerplate required to define a function in jquery?

(My example is with a callback but it could apply to any anon function.)

$('#dialog').load('/index.cgi',{p:'myform'}, function(){ ajaxify_form() });

What I would like is to do

$('#dialog').load('/index.cgi',{p:'myform'}, $.f(){ ajaxify_form() });

Thanks in advance.

+8  A: 

The boilerplate you have isn't required. Just pass in the function directly:

$('#dialog').load('/index.cgi',{p:'myform'}, ajaxify_form);

is for all intents and purposes equivalent to:

$('#dialog').load('/index.cgi',{p:'myform'}, function() { ajaxify_form(); });

except that the meaning of this will differ within the function.

Note: don't do it this way:

$('#dialog').load('/index.cgi',{p:'myform'}, ajaxify_form());

as that does something completely different. Instead of passing in the function you pass in what the function returns.

cletus
The only difference is that the `this` keyword, inside the `ajaxify_form` function, in the first example will refer to the `#dialog` DOM element, in the second example, it will refer to the global object (`window`).
CMS