且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将函数传递给 submitHandler 回调

更新时间:2023-09-06 17:45:58

您可以使用 bind 在这里.

You can use bind here.

bind 环绕一个函数引用,允许您将作用域和变量传递给目标函数:

bind wraps around a function reference allowing you to pass the scope and variables to the targeted function:

function.bind(thisArg[, arg1[, arg2[, ...]]])

function.bind(thisArg[, arg1[, arg2[, ...]]])

参数:

  • thisArg:调用绑定函数时作为 this 参数传递给目标函数的值.如果绑定函数是使用 new 运算符构造的,则该值将被忽略.
  • arg1, arg2, ...在调用目标函数时附加到提供给绑定函数的参数的参数.

源 MDN

var mainSubmitHandler=function(form, callback) {
    //do a bunch of stuff
    if (typeof(callBack) != "undefined" && Object.prototype.toString.call(callBack) === "[object Function]") //sanity check. Check if callback is truly a function and exists.
    {
        callback(form);
    }
};

var subSubmitHandler=function(form) {
    //do some stuff
};

// uses jQuery validation plugin
var validator=$("#form1").validate({
    rules: {},
    messages: {},
    submitHandler: mainSubmitHandler.bind(null, form, subSubmitHandler); //first argument is set to null. This passes the this argument of the targeted function.
});