JavaScript: 콜백 함수에 파라미터 전달
다음과 같이 사용되는 함수에 몇 가지 파라미터를 전달하려고 합니다.callback
,내가 어떻게 그럴 수 있을까?
제 시도는 이렇습니다.
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);
});
당신의 질문은 불분명합니다.보다 심플한 방법으로 이 작업을 수행할 수 있는 방법은 Function.protype의 멤버인ECMAScript 5th Edition 메서드 .bind()를 참조하십시오.이를 사용하여 다음과 같은 작업을 수행할 수 있습니다.
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)));
};
};
}
콜백 함수에 전달될 파라미터의 수가 불분명한 경우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>
자신의 코드가 아닌 다른 함수에 의해 콜백이 호출되어 추가 파라미터를 추가하는 시나리오의 새로운 버전.
예를 들어 성공 콜백과 에러 콜백이 있는 네스트된 콜이 많다고 가정합니다.이 예에서는 각진 약속을 사용하지만 콜백이 있는 자바스크립트 코드는 동일합니다.
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");
, , 하다, 하다, 하다, 하다, 하다, 하다, 하다, 하다, , 하다, 하는 함수에 어떤 매개
callback
좋을까요가가어 떻떻 ?럴? ???
를 이렇게 을 내포하고 것 같아요.callbackTester(tryMe, "hello", "goodbye")
이렇게 하려면 Rest 연산자(...)를 사용합니다.이 연산자는 함수가 수신한 인수를 받아 실제 배열로 덤프합니다.이러한 인수는 다음 명령에서 액세스하기 위해 사용됩니다.callback
★★★★★★ 。
에서도 ''를 할 수 할 수 .arguments
조용히' 해야 해요.★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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');
최근 이 문제에 직면했을 때 (특히 부모 함수에 콜백과 관련되지 않은 다른 작업을 수행하는 여러 인수가 있는 경우)는 인수로 전달되는 화살표 함수에 배치된 콜백을 받습니다.
function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester(callback, someArg, AnotherArg) {
callback();
}
callbackTester(()=> tryMe("hello", "goodbye"), "someArg", "AnotherArg");
...혹은 단순히 다른 일을 하는 데 여러 개의 논쟁이 없는 경우.
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);
}
});
주로 사용하는 기능을 사용하여this
value. 이 하지 않고 .bind()
제공된 인수 시퀀스와 함께 새 함수를 반환합니다.
예:
function foo(param1, param2, param3) {
console.log(param1, param2, param3);
}
setTimeout(foo.bind(null, 'foo', 'bar', 'baz'), 1000);
위의 스니펫에서 setTimeout 함수는 2개의 인수, 콜백 함수 및 호출되는 함수의 최소 시간(ms)을 사용합니다.따라서 콜백 함수를 전달할 때는 바인드를 사용하여 파라미터를 지정합니다.
첫는 ": bind"로 입니다.this
는 그런 거에 이 없기 에 그런 거에 대해서 관심이 없어요.null
바인드 내의 후속 파라미터가 콜백 파라미터가 됩니다.
언급URL : https://stackoverflow.com/questions/3458553/javascript-passing-parameters-to-a-callback-function
'itsource' 카테고리의 다른 글
Django가 실행 중인 원시 SQL 쿼리를 확인하는 방법은 무엇입니까? (0) | 2022.09.16 |
---|---|
느린 MYSQL 쿼리, 인덱스 이해 도움말 필요 (0) | 2022.09.16 |
구조물의 특별한 점은 무엇입니까? (0) | 2022.09.14 |
Java RegEx는 대소문자를 구분하지 않습니까? (0) | 2022.09.14 |
com.mysql.jdbc 클래스를 로드하고 있습니다.운전기사님.이것은 권장되지 않습니다.새로운 드라이버 클래스는 'com.mysql.cj.jdbc'입니다.드라이버 (0) | 2022.09.14 |