Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - Running a function that creates a click event twice causes the click event to happen twice with one click

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should solve your problem:

var tester = []

function TestA() {
  // First remove click handler and set a new one
  $("someobject").off("click").one("click", function () {
    tester.push("hello")
  })
}

TestA()

Here is a small example in jsfiddle https://jsfiddle.net/yusmneb1/

Please note: To achieve some kind of cheating protection, you should consider server side validation of your game logic. Javascript can be manipulated by the user easily. Here is a link to a question about that topic: How to prevent html/JavaScript code modification


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...