JavaScript:将参数传递给回调函数

时间:2022-12-05 19:20:57

I'm trying to pass some parameter to a function used as callback, how can I do that?

我尝试将一些参数传递给一个函数作为回调函数,我该怎么做呢?

function tryMe (param1, param2) {
    alert (param1 + " and " + param2);
}

function callbackTester (callback, param1, param2) {
    callback (param1, param2);
}

callbackTester (tryMe, "hello", "goodbye");

10 个解决方案

#1


203  

If you want something slightly more general, you can use the arguments variable like so:

如果你想要更一般的东西,你可以使用参数变量,比如:

function tryMe (param1, param2) {
    alert(param1 + " and " + param2);
}

function callbackTester (callback) {
    callback (arguments[1], arguments[2]);
}

callbackTester (tryMe, "hello", "goodbye");

But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)

但是,否则,您的示例工作得很好(参数[0]可以用来代替测试人员中的回调)

#2


181  

This would also work:

这也工作:

// callback function
function tryMe (param1, param2) { 
    alert (param1 + " and " + param2); 
} 

// callback executer 
function callbackTester (callback) { 
    callback(); 
} 

// test function
callbackTester (function() {
    tryMe("hello", "goodbye"); 
}); 

Another Scenario :

另一个场景:

// callback function
function tryMe (param1, param2, param3) { 
    alert (param1 + " and " + param2 + " " + param3); 
} 

// callback executer 
function callbackTester (callback) { 
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing" ;

//call the callback when we have the data
    callback(extraParam); 
} 

// test function
callbackTester (function(k) {
    tryMe("hello", "goodbye", k); 
}); 

#3


51  

Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

你的问题还不清楚。如果您想知道如何用更简单的方法实现这一点,您应该看看ECMAScript第5版方法.bind(),它是Function.prototype的成员。使用它,你可以做这样的事情:

function tryMe (param1, param2) {
    alert (param1 + " and " + param2);
}

function callbackTester (callback) {
    callback();
}

callbackTester(tryMe.bind(null, "hello", "goodbye"));

You can also use the following code, which adds the method if it isn't available in the current browser:

您还可以使用以下代码,如果在当前浏览器中无法使用该方法,则添加该方法:

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

Example

例子

bind() - PrototypeJS Documentation

bind()——PrototypeJS文档

#4


9  

When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).

当您有一个回调,这个回调将由除您的代码之外的其他东西以特定数量的参数调用,并且您希望传递附加的参数时,您可以将一个包装函数作为回调传递,并且在包装器内部传递附加的参数。

function login(accessedViaPopup) {
    //pass FB.login a call back function wrapper that will accept the
    //response param and then call my "real" callback with the additional param
    FB.login(function(response){
        fb_login_callback(response,accessedViaPopup);
    });
}

//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
    //do stuff
}

#5


4  

Wrap the 'child' function(s) being passed as/with arguments within function wrappers to prevent them being evaluated when the 'parent' function is called.

将“子”函数封装在函数包装内,以防止在调用“父”函数时对其进行评估。

function outcome(){
    return false;
}

function process(callbackSuccess, callbackFailure){
    if ( outcome() )
        callbackSuccess();
    else
        callbackFailure();
}

process(function(){alert("OKAY");},function(){alert("OOPS");})

#6


3  

Code from a question with any number of parameters and a callback context:

来自一个有任意数量参数和回调上下文的问题的代码:

function SomeFunction(name) {
    this.name = name;
}
function tryMe(param1, param2) {
    console.log(this.name + ":  " + param1 + " and " + param2);
}
function tryMeMore(param1, param2, param3) {
    console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
}
function callbackTester(callback, callbackContext) {
    callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
}
callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");

// context1: hello and goodbye
// context2: hello and goodbye and even hasta la vista

#7


1  

Use curried function as in this simple example.

使用curry过的函数,就像这个简单的例子一样。

const BTN = document.querySelector('button')
const RES = document.querySelector('p')

const changeText = newText => () => {
  RES.textContent = newText
}

BTN.addEventListener('click', changeText('Clicked!'))
<button>ClickMe</button>
<p>Not clicked<p>

#8


1  

If you are not sure how many params are you going to be passed into callback functions. Using apply.

如果您不确定有多少个参数,您将被传递到回调函数中。使用申请。

function tryMe (param1, param2) {
  alert (param1 + " and " + param2);
}

function callbackTester(callback,params){
    callback.apply(this,params);
}

callbackTester(tryMe,['hello','goodbye']);

#9


0  

A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.

该场景的新版本中,回调将由其他函数调用,而不是您自己的代码,您需要添加额外的参数。

For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.

例如,让我们假设您有很多成功和错误回调的嵌套调用。在本例中,我将使用角承诺,但是任何带有回调的javascript代码都是相同的。

someObject.doSomething(param1, function(result1) {
  console.log("Got result from doSomething: " + result1);
  result.doSomethingElse(param2, function(result2) {
    console.log("Got result from doSomethingElse: " + result2);
  }, function(error2) {
    console.log("Got error from doSomethingElse: " + error2);
  });
}, function(error1) {
  console.log("Got error from doSomething: " + error1);
});

Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:

现在,您可能希望通过定义一个用于记录错误的函数来消除代码的混乱,保留错误的起源,以便进行调试。这是你如何着手重构你的代码:

someObject.doSomething(param1, function (result1) {
  console.log("Got result from doSomething: " + result1);
  result.doSomethingElse(param2, function (result2) {
    console.log("Got result from doSomethingElse: " + result2);
  }, handleError.bind(null, "doSomethingElse"));
}, handleError.bind(null, "doSomething"));

/*
 * Log errors, capturing the error of a callback and prepending an id
 */
var handleError = function (id, error) {
  var id = id || "";
  console.log("Got error from " + id + ": " + error);
};

The calling function will still add the error parameter after your callback function parameters.

调用函数仍然会在回调函数参数之后添加错误参数。

#10


0  

I was looking for the same thing and end up with the solution and here it's a simple example if anybody wants to go through this.

我也在寻找同样的东西,最后得到了解这里有一个简单的例子,如果有人想看的话。

var FA = function(data){
   console.log("IN A:"+data)
   FC(data,"LastName");
};
var FC = function(data,d2){
   console.log("IN C:"+data,d2)
};
var FB = function(data){
   console.log("IN B:"+data);
    FA(data)
};
FB('FirstName')

Also posted on the other question here

还有一个问题

#1


203  

If you want something slightly more general, you can use the arguments variable like so:

如果你想要更一般的东西,你可以使用参数变量,比如:

function tryMe (param1, param2) {
    alert(param1 + " and " + param2);
}

function callbackTester (callback) {
    callback (arguments[1], arguments[2]);
}

callbackTester (tryMe, "hello", "goodbye");

But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)

但是,否则,您的示例工作得很好(参数[0]可以用来代替测试人员中的回调)

#2


181  

This would also work:

这也工作:

// callback function
function tryMe (param1, param2) { 
    alert (param1 + " and " + param2); 
} 

// callback executer 
function callbackTester (callback) { 
    callback(); 
} 

// test function
callbackTester (function() {
    tryMe("hello", "goodbye"); 
}); 

Another Scenario :

另一个场景:

// callback function
function tryMe (param1, param2, param3) { 
    alert (param1 + " and " + param2 + " " + param3); 
} 

// callback executer 
function callbackTester (callback) { 
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing" ;

//call the callback when we have the data
    callback(extraParam); 
} 

// test function
callbackTester (function(k) {
    tryMe("hello", "goodbye", k); 
}); 

#3


51  

Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

你的问题还不清楚。如果您想知道如何用更简单的方法实现这一点,您应该看看ECMAScript第5版方法.bind(),它是Function.prototype的成员。使用它,你可以做这样的事情:

function tryMe (param1, param2) {
    alert (param1 + " and " + param2);
}

function callbackTester (callback) {
    callback();
}

callbackTester(tryMe.bind(null, "hello", "goodbye"));

You can also use the following code, which adds the method if it isn't available in the current browser:

您还可以使用以下代码,如果在当前浏览器中无法使用该方法,则添加该方法:

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

Example

例子

bind() - PrototypeJS Documentation

bind()——PrototypeJS文档

#4


9  

When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).

当您有一个回调,这个回调将由除您的代码之外的其他东西以特定数量的参数调用,并且您希望传递附加的参数时,您可以将一个包装函数作为回调传递,并且在包装器内部传递附加的参数。

function login(accessedViaPopup) {
    //pass FB.login a call back function wrapper that will accept the
    //response param and then call my "real" callback with the additional param
    FB.login(function(response){
        fb_login_callback(response,accessedViaPopup);
    });
}

//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
    //do stuff
}

#5


4  

Wrap the 'child' function(s) being passed as/with arguments within function wrappers to prevent them being evaluated when the 'parent' function is called.

将“子”函数封装在函数包装内,以防止在调用“父”函数时对其进行评估。

function outcome(){
    return false;
}

function process(callbackSuccess, callbackFailure){
    if ( outcome() )
        callbackSuccess();
    else
        callbackFailure();
}

process(function(){alert("OKAY");},function(){alert("OOPS");})

#6


3  

Code from a question with any number of parameters and a callback context:

来自一个有任意数量参数和回调上下文的问题的代码:

function SomeFunction(name) {
    this.name = name;
}
function tryMe(param1, param2) {
    console.log(this.name + ":  " + param1 + " and " + param2);
}
function tryMeMore(param1, param2, param3) {
    console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
}
function callbackTester(callback, callbackContext) {
    callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
}
callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");

// context1: hello and goodbye
// context2: hello and goodbye and even hasta la vista

#7


1  

Use curried function as in this simple example.

使用curry过的函数,就像这个简单的例子一样。

const BTN = document.querySelector('button')
const RES = document.querySelector('p')

const changeText = newText => () => {
  RES.textContent = newText
}

BTN.addEventListener('click', changeText('Clicked!'))
<button>ClickMe</button>
<p>Not clicked<p>

#8


1  

If you are not sure how many params are you going to be passed into callback functions. Using apply.

如果您不确定有多少个参数,您将被传递到回调函数中。使用申请。

function tryMe (param1, param2) {
  alert (param1 + " and " + param2);
}

function callbackTester(callback,params){
    callback.apply(this,params);
}

callbackTester(tryMe,['hello','goodbye']);

#9


0  

A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.

该场景的新版本中,回调将由其他函数调用,而不是您自己的代码,您需要添加额外的参数。

For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.

例如,让我们假设您有很多成功和错误回调的嵌套调用。在本例中,我将使用角承诺,但是任何带有回调的javascript代码都是相同的。

someObject.doSomething(param1, function(result1) {
  console.log("Got result from doSomething: " + result1);
  result.doSomethingElse(param2, function(result2) {
    console.log("Got result from doSomethingElse: " + result2);
  }, function(error2) {
    console.log("Got error from doSomethingElse: " + error2);
  });
}, function(error1) {
  console.log("Got error from doSomething: " + error1);
});

Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:

现在,您可能希望通过定义一个用于记录错误的函数来消除代码的混乱,保留错误的起源,以便进行调试。这是你如何着手重构你的代码:

someObject.doSomething(param1, function (result1) {
  console.log("Got result from doSomething: " + result1);
  result.doSomethingElse(param2, function (result2) {
    console.log("Got result from doSomethingElse: " + result2);
  }, handleError.bind(null, "doSomethingElse"));
}, handleError.bind(null, "doSomething"));

/*
 * Log errors, capturing the error of a callback and prepending an id
 */
var handleError = function (id, error) {
  var id = id || "";
  console.log("Got error from " + id + ": " + error);
};

The calling function will still add the error parameter after your callback function parameters.

调用函数仍然会在回调函数参数之后添加错误参数。

#10


0  

I was looking for the same thing and end up with the solution and here it's a simple example if anybody wants to go through this.

我也在寻找同样的东西,最后得到了解这里有一个简单的例子,如果有人想看的话。

var FA = function(data){
   console.log("IN A:"+data)
   FC(data,"LastName");
};
var FC = function(data,d2){
   console.log("IN C:"+data,d2)
};
var FB = function(data){
   console.log("IN B:"+data);
    FA(data)
};
FB('FirstName')

Also posted on the other question here

还有一个问题