[英]Javascript Callback with Parameters and Return Value
Here is my dilemma, I have a series of functions that get called and I am using callbacks to execute a function when they are complete. 这是我的困境,我有一系列被调用的函数,我正在使用回调来完成一个函数。 The callback returns a value and that works great too, my problem is when I add parameters to the callback I can no longer access the returned value.
回调返回一个值,这也很有效,我的问题是当我向回调添加参数时,我无法再访问返回的值。 Here is an example what works:
这是一个有效的例子:
function myFunc1(x, y) {
/*do stuff*/
myFunc2(z, callback);
}
function callback(results) {
alert(results); /*this works!*/
}
This works great, the results returned are displayed. 这很好用,显示返回的结果。 My problem what I need to do is something like this:
我的问题是我需要做的是这样的:
function myFunc1(x, y) {
/*do stuff*/
myFunc2(z, callback(x,y));
}
function callback(x,y,results) {
alert(x); /*works!*/
alert(y); /*works!*/
alert(results); /*doesn't work :(*/
}
I need a way to access both the value return as well as my parameters. 我需要一种方法来访问值返回以及我的参数。 Is something like this possible??
这样的事可能吗?
You can use Function.prototype.bind
, like this 您可以像这样使用
Function.prototype.bind
myFunc2(z, callback.bind(null, x, y));
bind
function will return a new function with the first parameter as the context and the next parameters are the actual parameters passed to callback
when invoked. bind
函数将返回一个新函数,第一个参数作为上下文,下一个参数是callback
时传递给callback
的实际参数。
You will need to not call the callback
immediately, but instead make a function that calls callback
later with the expected arguments: 您将不需要立即调用
callback
,而是创建一个稍后使用预期参数调用callback
的函数:
function myFunc1(x, y) {
/*do stuff*/
myFunc2(z, function(results) {
callback(x, y, results);
});
}
The .bind()
variant proposed by @thefourtheye is basically 1 a shortcut for this function expression. @thefourtheye提出的
.bind()
变体基本上是1这个函数表达式的快捷方式。
1: rather for function(results) { return callback.call(null, x, y, results) }
, also it would pass through more arguments than only results
, and it would evaluate x
and y
at the time of the bind
call. 1:而不是
function(results) { return callback.call(null, x, y, results) }
,它也会传递更多的参数而不仅仅是results
,它会在bind
调用时评估x
和y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.