簡體   English   中英

JavaScript:將參數傳遞給回調 function

[英]JavaScript: Passing parameters to a callback function

我正在嘗試將一些參數傳遞給用作callback的 function ,我該怎么做?

這是我的嘗試:

 function tryMe(param1, param2) { alert(param1 + " and " + param2); } function callbackTester(callback, param1, param2) { callback(param1, param2); } callbackTester(tryMe, "hello", "goodbye");

如果你想要更一般的東西,你可以像這樣使用參數變量:

 function tryMe(param1, param2) { alert(param1 + " and " + param2); } function callbackTester(callback) { callback(arguments[1], arguments[2]); } callbackTester(tryMe, "hello", "goodbye");

但除此之外,您的示例工作正常( arguments[0]可用於代替測試器中的callback

這也可以:

 // callback function function tryMe(param1, param2) { alert(param1 + " and " + param2); } // callback executer function callbackTester(callback) { callback(); } // test function callbackTester(function() { tryMe("hello", "goodbye"); });

另一個場景:

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

你的問題不清楚。 如果您要問如何以更簡單的方式執行此操作,您應該查看 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 文檔

如果您不確定將有多少參數傳遞給回調函數,請使用apply函數。

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

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

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

當您有一個回調,該回調將被具有特定數量參數的代碼以外的其他東西調用,並且您想傳入額外的參數時,您可以將包裝函數作為回調傳遞,並在包裝​​內部傳遞額外的參數。

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
}

在函數包裝器中包裝作為/帶有參數傳遞的“子”函數,以防止在調用“父”函數時對它們進行評估。

function outcome(){
    return false;
}

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

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

來自具有任意數量參數和回調上下文的問題的代碼:

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

在這個簡單的例子中使用柯里化函數。

 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>

一個新版本,用於回調將由某個其他函數而不是您自己的代碼調用的場景,並且您想要添加其他參數。

例如,假設您有很多帶有成功和錯誤回調的嵌套調用。 我將在此示例中使用 angular 承諾,但任何帶有回調的 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);
});

現在,您可能希望通過定義一個記錄錯誤的函數來整理代碼,保留錯誤的來源以進行調試。 這是您重構代碼的方式:

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

調用函數仍會在回調函數參數之后添加錯誤參數。

讓我給你一個使用回調的非常簡單的 Node.js 風格的例子:

/**
 * Function expects these arguments: 
 * 2 numbers and a callback function(err, result)
 */
var myTest = function(arg1, arg2, callback) {
  if (typeof arg1 !== "number") {
    return callback('Arg 1 is not a number!', null); // Args: 1)Error, 2)No result
  }
  if (typeof arg2 !== "number") {
    return callback('Arg 2 is not a number!', null); // Args: 1)Error, 2)No result
  }
  if (arg1 === arg2) {
    // Do somethign complex here..
    callback(null, 'Actions ended, arg1 was equal to arg2'); // Args: 1)No error, 2)Result
  } else if (arg1 > arg2) {
    // Do somethign complex here..
    callback(null, 'Actions ended, arg1 was > from arg2'); // Args: 1)No error, 2)Result
  } else {
    // Do somethign else complex here..
    callback(null, 'Actions ended, arg1 was < from arg2'); // Args: 1)No error, 2)Result
  }
};


/**
 * Call it this way: 
 * Third argument is an anonymous function with 2 args for error and result
 */
myTest(3, 6, function(err, result) {
  var resultElement = document.getElementById("my_result");
  if (err) {
    resultElement.innerHTML = 'Error! ' + err;
    resultElement.style.color = "red";
    //throw err; // if you want
  } else {
    resultElement.innerHTML = 'Result: ' + result;
    resultElement.style.color = "green";
  }
});

以及將呈現結果的 HTML:

<div id="my_result">
  Result will come here!
</div>

你可以在這里玩它: https : //jsfiddle.net/q8gnvcts/ - 例如嘗試傳遞字符串而不是數字: myTest('some string', 6, function(err, result) ..並查看結果。

我希望這個例子有幫助,因為它代表了回調函數的基本思想。

function tryMe(param1, param2) {
  console.log(param1 + " and " + param2);
}

function tryMe2(param1) {
  console.log(param1);
}

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



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

callbackTester(tryMe2, "hello");

閱讀有關傳播語法的更多信息

最近面對這個,要得到它(特別是如果父 function 有多個 arguments 做與回調無關的不同事情,就是將回調放置在箭頭 ZC1C425268E68385D1AB5074C17A9 中作為參數傳遞。

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

function callbackTester(callback, someArg, AnotherArg) {
  callback();
  
}

callbackTester(()=> tryMe("hello", "goodbye"), "someArg", "AnotherArg");

...或者只是如果您沒有多個 arguments 做其他事情。

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

function callbackTester(callback) {
  callback();
}

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

我一直在尋找同樣的東西並最終得到解決方案,如果有人想通過這個,這是一個簡單的例子。

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')

也在這里發布了另一個問題

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

我試圖將一些參數傳遞給用作callback的函數,我該怎么做?

我認為他是在暗示他想調用這個函數callbackTester(tryMe, "hello", "goodbye") 為此,我們可以使用Rest Operator (...) 該運算符獲取函數接收的參數並將它們轉儲到我們將在callback函數中訪問的真實數組中。

現在,其他一些開發人員可能也會爭辯說我們可以使用arguments “array”。 那會好的,但我們應該小心。 arguments不是真正的數組,而是具有長度屬性的類數組對象。

這是使用 Rest 運算符的工作片段:

 function tryMe(params) { console.log(params.join(', ')); } function callbackTester(callback, ...params) { callback(params); } callbackTester(tryMe, 'hello', 'goodbye', 'hi again'); callbackTester(tryMe, 'hello', 'goodbye'); callbackTester(tryMe, 'hello');

只需使用主要用於設置this值的bind() function。 但是,我們也可以使用它來傳遞參數而不調用 function,因為bind()返回一個新的 function 並提供了 arguments 的序列。

例子:

 function foo(param1, param2, param3) { console.log(param1, param2, param3); } setTimeout(foo.bind(null, 'foo', 'bar', 'baz'), 1000);

In the snippet above, the setTimeout function takes 2 arguments, the callback function and a minimum time in ms for the function to be called, so when passing the callback function we're going to use bind and specify the parameters

注意:bind 的第一個參數是我們要設置的this的值,因為我們對此不感興趣,所以傳遞了null ,bind 中的后續參數將作為回調的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM