传递函数到submitHandler回调

时间:2015-03-21 12:12:11

标签: javascript jquery jquery-validate anonymous-function

我将mainSubmitHandler用于多个页面,如果有必要,我愿意将其定义为全局变量。但是,mainSubmitHandler需要进行一些调整,我正在使用subSubmitHandler处理此问题。我没有将subSubmitHandler作为另一个全局变量,而是如何将其作为agrument传递给mainSubmitHandler

var mainSubmitHandler=function(form) {
    //do a bunch of stuff
    subSubmitHandler(form);
};

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

// uses jQuery validation plugin
var validator=$("#form1").validate({
    rules: {},
    messages: {},
    submitHandler: mainSubmitHandler
});

2 个答案:

答案 0 :(得分:3)

您可以在此处使用bind

bind包含一个函数引用,允许您将范围和变量传递给目标函数:

  

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.
});

答案 1 :(得分:1)

将该函数作为附加参数传递:

var mainSubmitHandler=function(form, secondFunction) {
    //do a bunch of stuff
    secondFunction(form);
};

mainSubmitHandler(form, subSubmitHandler);

这是你的意思吗?

您可以将无限的参数传递给函数,所有这些参数都是可选的。你甚至可以这样做:

function doSomething(){ // not defining any arguments
    console.log( arguments); // will output everything you passed the function
}

doSomething( "Hello", someOtherFunction );

这也有效:

function doSomething(arg1, arg2){ // defining 2 arguments, but will accept more if given
    console.log( arguments); // will output everything you passed the function
}

doSomething( "First", "Second", someFunction, "third");

这就是为什么许多严格的人讨厌Javascript,为什么我喜欢它=)