[英]Create a function which returns on event listener being triggered
In JavaScript, I have an event listener and I have a separate function that needs to return a value only when the listener is triggered.在 JavaScript 中,我有一个事件侦听器,并且有一个单独的函数,该函数仅在触发侦听器时才需要返回一个值。
Example of what I am looking for:我正在寻找的示例:
document.getElementById("myBtn").addEventListener("click", function(){ alert("Hello World!"); });
function test(){
//check if myBtn has been pressed then return 1;
//otherwise keep waiting and don't return anything until myBtn is clicked.
}
How can I do something like this?我怎么能做这样的事情?
var is_button_pressed = 0;
document.getElementById("myBtn").addEventListener("click", function(){
is_button_pressed = 1;
});
function test(){
return is_button_pressed===1?1:undefined;
}
You could just use test() inside your original event listener and then for the event listener inside test(), use a closure to check the value of myBtn, and then return the value you want.您可以在原始事件侦听器中使用 test() ,然后在 test() 中使用事件侦听器,使用闭包检查 myBtn 的值,然后返回所需的值。
Honestly, I don't understand the point of 2 event listeners inside each other.老实说,我不明白彼此内部的 2 个事件侦听器的意义。 For a RESTful request, why would you want to pause the request.
对于 RESTful 请求,为什么要暂停请求。 You could just as simply capture the parameters of the request with the 1st button, and use the 2nd button to actually send the request.
您可以简单地使用第一个按钮捕获请求的参数,然后使用第二个按钮实际发送请求。 This is a lot easier to code and reason about.
这更容易编码和推理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.