javascript - 将回调函数作为参数传递

标签 javascript

我正在调用如下所示的函数。在这里,我还传递了回调函数,该函数只能在特定表单提交之后调用,而不是在此之前调用。

<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

        }
     }
}();

问题是在单击OPEN DIALOG后立即调用alert(p1+"cb "+p2);。不应该是这样的。应该只在我想要的时候调用它。有什么问题

最佳答案

问题是 aboutBizzNs.callback 立即调用作为参数提供的函数。

<小时/>

与以下创建并返回 closure (function) 的内容进行比较它将调用在调用它本身时提供的函数:

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

我还会使用apply ,如下所示,可以使用任意数量的“绑定(bind)”参数..

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

..但是这是一个相当常见的操作,并且已经被 Function.prototype.bind 支持。 (这是 ES5 的一部分,并且可以在其他浏览器中进行填充)。因此,原来的..

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

..可以写成..

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

..在这里达到同样的效果。不同之处在于回调 (cb) 函数内的 this 可能有所不同,因为 bind 不允许“传递”这个

或者,忘记所有这些特殊函数并简单地包装回调..

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

关于javascript - 将回调函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594372/

相关文章:

javascript - createElement 函数不适用于 MAC Safari

javascript - 创建一个 Ahead-of-Time (AOT) 编译库供 Angular 应用程序使用

javascript - 光滑 slider 中心模式不起作用

javascript - 如何使用javascript检测音量增大按钮的点击事件?

javascript - D3 对象恒常性不适用于键功能。 Enter 和 Update 每次都包含所有元素

javascript - React Native 组件未在 map() 迭代器内渲染

javascript - DHTMLX Scheduler 具有自定义时间线周/月 View ?

javascript - 替换每个在 jQuery 中不起作用

javascript - 使用 sketch.js 为移动网页绘制 Canvas 会在触摸时重置

javascript - 使用身份验证 header 发出跨域请求