开发者

Javascript (jQuery) Syntax on button click action

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜