views:

60

answers:

2

I have the following Javascript:

var form = $(formArray[i]);
var formAction = form.attr("action");
var button = form.find("input:submit");
button.click(function (formAction, form) {
  return function () {
    var formAjaxAction = formAction.replace(originalString, ajaxString);
    ajaxPostHandler(formAjaxAction, onSuccessFunc, function () {
      errorHandler(errorMsg, widget);
    }, widget, "internalAjaxQueue", false, form);
    return false;
  };
}(formAction, form));

What does the final line do? Invoke the action?

+3  A: 

This code defines a function that takes two parameters function (formAction, form) and returns a click handler. return function() { ... };.

It then calls the function with the two parameters (the last line) and passes the function that it returns to jQuery's click function.

The reason to do it this way is that if you subsequently assign something else to the form or formAction variables, the handler will not be affected.

SLaks
thanks, would up-vote if had rep
Ben Aston
+2  A: 

It works like this:

function (formAction, form) {
  return function () {
    var formAjaxAction = formAction.replace(originalString, ajaxString);
    ajaxPostHandler(formAjaxAction, onSuccessFunc, function () {
      errorHandler(errorMsg, widget);
    }, widget, "internalAjaxQueue", false, form);
    return false;
  };
}

defines a function (obviously) but inside:

{function(...) ... }

it is scoped not to be visible outside that context. That function returns an anonymous function.

(function(...) ... }(formAction, form)

calls that function with those two arguments and:

button.click(...);

assigns that anonymous function to be a click event handler for the button.

It's a fairly obfuscated way to write what it's doing.

cletus
thanks, would up-vote if had rep
Ben Aston
@Ben Aston. If you find an answer particularly correct, you can mark it as such.
Tracker1