I'm working on a game but I boiled down the functionality here.
TestA() is designed to create a click event on a certain object. When that object is clicked, it updates an array, tester.
The click event shouldn't ALWAYS be there, which is why I create it with TestA()
, and then turn it off inside of TestA()
.
However, when I run two TestA()
functions back-to-back, the array updates twice on one click, instead of the expected behavior of once, then I need to click again for the second update.
I'm trying to test:
var tester = []
function TestA() {
$("someobject").click(function () {
tester.push("hello")
$(this).off()
})
}
TestA()
----> running this by itself once makes tester = ["hello"]
after one click.
TestA()
TestA()
-------> running these two back-to-back, after ONE click tester becomes ["hello","hello]
I understand that Javascript will evaluate everything simultaneously (I posted a similar question in the past), but I do need to make sure people can't cheat in this game!
Again, my goal is to have TestA()
add the click event, have it work once on click and not again until the second TestA()
puts the event out again.
-I suppose a workaround is to have event listeners all over the place with an "if" inside its function that checks to see if the function can even be evaluated upon a click - but I'd much rather only create the click events in small windows of time.
question from:
https://stackoverflow.com/questions/65858498/running-a-function-that-creates-a-click-event-twice-causes-the-click-event-to-ha 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…