本文介绍了将函数传递给 submitHandler 回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 mainSubmitHandler 用于多个页面,并且愿意在必要时将其定义为全局变量.但是,mainSubmitHandler 需要一些调整,我正在使用 subSubmitHandler 处理这个问题.我如何将 subSubmitHandler 作为另一个全局变量而不是将它作为参数传递给 mainSubmitHandler?

I use mainSubmitHandler for multiple pages, and am willing to define it as a global variable if necessary. mainSubmitHandler, however, requires some tweaking, and I am handling this by using subSubmitHandler. Instead of having subSubmitHandler as another global variable, how can I pass it as an agrument to 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
});

推荐答案

您可以使用 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[, ...]]])

参数:

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

这篇关于将函数传递给 submitHandler 回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:23