[英]Passing callback function as parameter
我正在调用如下函数。 在这里,我还传递了仅应在提交特定表单之后才调用的回调函数。
<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
}
}
}();
问题是alert(p1+" cb "+p2);
单击“ OPEN DIALOG
后立即调用。 不应该那样。 仅在需要时才应调用它。 问题是什么
问题在于aboutBizzNs.callback
立即调用作为参数提供的函数。
与下面的代码进行比较,后者创建并返回一个闭包(函数) ,该闭包将在调用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]);}
}
}
我还将使用apply
,如下所示,这样就可以使用任意数量的“绑定”参数。
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')
..在这里同样的效果。 的不同点在于this
回调(内部cb
)函数可以作为不同bind
不允许“通过”的this
。
或者,只需忽略所有这些特殊功能,然后将回调包装为..
function () { myNamespace.cb('p1','p2') }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.