我试图传递一些参数的函数用作回调,我怎么能这样做?
这是我的尝试: 函数tryMe(param1, param2) { Alert (param1 + " and " + param2); } 函数callbackTester(回调,param1, param2) { 回调(param1 param2); } callbackTester(tryMe, "hello", "goodbye");
我试图传递一些参数的函数用作回调,我怎么能这样做?
这是我的尝试: 函数tryMe(param1, param2) { Alert (param1 + " and " + param2); } 函数callbackTester(回调,param1, param2) { 回调(param1 param2); } callbackTester(tryMe, "hello", "goodbye");
当前回答
在这个简单的例子中使用curry函数。
const BTN = document.querySelector('button') const RES = document.querySelector('p') const changeText = newText => () => { RES.textContent = newText } BTN。addEventListener(“点击”,changeText(点击!)) <按钮> ClickMe > < /按钮 < p >不点击< p >
其他回答
当你有一个回调函数,它将被你的代码以外的东西调用,具有特定数量的参数,你想传递额外的参数,你可以传递一个包装器函数作为回调,并在包装器内部传递额外的参数。
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
}
你的问题不清楚。如果你在问如何以更简单的方式做到这一点,你应该看看ECMAScript第5版方法.bind(),它是Function.prototype的成员。使用它,你可以做这样的事情:
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback) {
callback();
}
callbackTester(tryMe.bind(null, "hello", "goodbye"));
你也可以使用下面的代码,它会在当前浏览器中不可用时添加方法:
// 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)));
};
};
}
例子
bind() - PrototypeJS文档
我试图传递一些参数的函数用作回调,我怎么能这样做?
我认为他是在暗示他想调用这个callbackTester函数(tryMe, "hello", "goodbye")。为此,我们可以使用Rest操作符(…)。该操作符接受函数接收到的参数,并将它们转储到一个实数组中,我们将在回调函数中使用该数组进行访问。
现在,其他一些开发人员可能也认为我们可以使用参数"array"。那很好,但我们要小心。Arguments不是一个真正的数组,而是一个具有length属性的类数组对象。
下面是一个使用Rest操作符的工作代码片段:
函数tryMe(参数){ console.log(参数。加入(',')); } 函数callbackTester(回调,…params) { 回调(params); } callbackTester(tryMe, 'hello', 'goodbye', 'hi again'); callbackTester(tryMe, 'hello', 'goodbye'); callbackTester (tryMe '你好');
如果你想要一些更一般的东西,你可以像这样使用arguments变量:
函数tryMe(param1, param2) { Alert (param1 + " and " + param2); } 函数callbackTester(回调){ 回调参数(参数[1],[2]); } callbackTester(tryMe, "hello", "goodbye");
但除此之外,你的例子工作得很好(参数[0]可以用来代替测试器中的回调)
//Suppose function not taking any parameter means just add the GetAlterConfirmation(function(result) {});
GetAlterConfirmation('test','messageText',function(result) {
alert(result);
}); //Function into document load or any other click event.
function GetAlterConfirmation(titleText, messageText, _callback){
bootbox.confirm({
title: titleText,
message: messageText,
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
return _callback(result);
}
});