简体   繁体   English

为什么不会异步调用此回调

[英]Why is this callback not called asynchronously

The function asyncMsg is called immediately on clicking the start hooking button. 单击开始挂钩按钮后立即调用asyncMsg函数。 How do I change to call only when user clicks on press me button. 如何仅在用户点击“按我”按钮时更改为呼叫。 I need to pass the 2 items of data into this callback. 我需要将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>

I can see how if I just pass the function as in: 我可以看看如果我只是传递函数,如:

bindEvent(btn, 'click', asyncMsg);

then it is called asynchronously, but then how do I pass the 2 parameters? 然后它被异步调用,但是我如何传递2个参数?

You call the function immediately instead of passing the function itself to the bindEvent function - because calling the function is what happens when you use the () "operator" on a function. 你立即调用函数而不是将函数本身传递给bindEvent函数 - 因为调用函数是在函数上使用() “运算符”时发生的事情。

What you want instead is this: 你想要的是这样的:

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

The bind() method of a function returns another callable that will execute the function with the given context ( null in this case) and the provided parameters. 函数的bind()方法返回另一个callable,它将执行具有给定上下文的函数(在本例中为null )和提供的参数。

Another option that also works in older browsers would be creating an anonymous function which then calls your function: 另一个也适用于旧浏览器的选项是创建一个匿名函数,然后调用你的函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM