简体   繁体   English

将回调函数作为参数传递

[英]Passing callback function as parameter

I am calling a function like below. 我正在调用如下函数。 Here I am also passing callback function that should be called only after a particular form submit not before that. 在这里,我还传递了仅应在提交特定表单之后才调用的回调函数。

<div onClick="myNamespace.openDialog(par1,par2,myNamespace.callback(myNamespace.cb,'p1','p2'))">OPEN DIALOG</div>

var myNamespace = myNamespace || {};
myNamespace={
     return{
        cb:function(p1,p2){alert(p1+"  cb  "+p2);},
        callback:function(f){f(arguments[1],arguments[2]);},
        openDialog:function(p1,p2,f){
          // aboutBizzNs.cb should be called here only after form submit

        }
     }
}();

The problem is alert(p1+" cb "+p2); 问题是alert(p1+" cb "+p2); is called just after OPEN DIALOG is clicked. 单击“ OPEN DIALOG后立即调用。 It should not be like that. 不应该那样。 It should be called only when I want. 仅在需要时才应调用它。 What is the problem 问题是什么

The problem is that aboutBizzNs.callback immediately invokes the function supplied as an argument. 问题在于aboutBizzNs.callback 立即调用作为参数提供的函数。


Compare with the following which creates and returns a closure (function) which will invoke the function supplied when it iself is invoked: 与下面的代码进行比较,后者创建并返回一个闭包(函数) ,该闭包将在调用iself时调用提供的函数:

callback: function(f){
    // The f variable is bound in a closure below, which is returned immediately.
    // However, the f function is NOT invoked yet.
    // We also copy the arguments of this function invocation and expose
    // them via a variable which is also bound in the following closure.
    var boundArgs = Array.prototype.slice(arguments, 0);
    return function () {
        // Now f is invoked when this inner function is evaluated, which
        // should be in response to the event.
        return f(boundArgs[1], boundArgs[2]);}
    }
}

I'd also use apply , as in the following such than an arbitrary number of "bound" parameters can be used .. 我还将使用apply ,如下所示,这样就可以使用任意数量的“绑定”参数。

return function () {
    return f.apply(this, boundArgs.slice(1));
}

.. but this is a fairly common operation and is already supported by Function.prototype.bind (which is part of ES5 and shim-able in other browsers). .., 但这是一个相当常见的操作,并且已经由Function.prototype.bind (它是ES5的一部分,并且在其他浏览器中可填充)已支持。 As such, the original .. 因此,原始..

myNamespace.callback(myNamespace.cb,'p1','p2')

.. could be written as .. ..可以写成..

myNamespace.cb.bind(this,'p1','p2')

.. for the same effect here. ..在这里同样的效果。 A difference is the this inside the callback ( cb ) function may differ as bind doesn't allow a "pass through" of this . 的不同点在于this回调(内部cb )函数可以作为不同bind不允许“通过”的this

Or, just forget about all these special functions and simply wrap the callback as such .. 或者,只需忽略所有这些特殊功能,然后将回调包装为..

function () { myNamespace.cb('p1','p2') }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM