2013-03-17 3 views
0

asyncMsg 함수는 시작 후킹 단추를 클릭 할 때 즉시 호출됩니다. 사용자가 나를 누르는 버튼을 클릭 할 때만 전화를 걸려면 어떻게 변경해야합니까? 이 콜백에 2 개의 데이터 항목을 전달해야합니다.이 콜백이 비동기 적으로 호출되지 않는 이유

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<script type="text/javascript"> 

function bindEvent(el, eventName, eventHandler) { 
    if (el.addEventListener){ 
     el.addEventListener(eventName, eventHandler, false); 
    } else if (el.attachEvent){ 
     el.attachEvent('on'+eventName, eventHandler); 
    } 
} 

function asyncMsg(data, fldid) { 
    alert("asynchronous message with param1=" + data + " param2=" + fldid); 
} 

function dohooking() { 
    var toinsert = "Duck"; 
    var fldid = "10"; 
    var btn = document.getElementById("hookee"); 
    bindEvent(btn, 'click', asyncMsg(toinsert, fldid)); 
} 

</script> 

<title></title> 

</head> 
<body> 

<input type="button" id="sethooking" value="start hooking" onclick="dohooking();"> 
<br /> 

<input type="button" id="hookee" value="press me"> 
<br /> 

</body> 
</html> 

난 그냥 같이 기능을 전달하는 경우 어떻게 볼 수 있습니다 : 다음

bindEvent(btn, 'click', asyncMsg); 

가 비동기 적으로 호출됩니다,하지만 어떻게이 두 매개 변수를 전달하지?

답변

2

bindEvent 함수에 함수 자체를 전달하는 대신 즉시 함수를 호출합니다. 함수 호출은 함수에서 () "연산자"를 사용할 때 발생하기 때문에 발생합니다.

bindEvent(btn, 'click', asyncMsg.bind(null, toinsert, fldid)); 

함수의 bind() 방법은 주어진 컨텍스트 (이 경우 null) 및 제공된 매개 변수 기능을 실행할 다른 호출을 반환

은 당신이 대신 원하는 것은 이것이다. 또한 이전 버전의 브라우저에서 작동

또 다른 옵션은 다음 함수를 호출하는 익명 함수를 만드는 것입니다 :

bindEvent(btn, 'click', function() { 
    asyncMsg(toinsert, fldid); 
}); 
+0

참고 : 그런 바인딩을 사용하는 경우, 이벤트 객체가 인수 [2]에 전달됩니다, 일반적인 첫 번째 인수 대신. – bfavaretto

관련 문제