OnEvent within another onEvent allowed?

Oooh, this is a tricky misconception about how event handlers work. When you call onEvent() it creates a new event handler sitting in the background responding to events. Once you’ve created an event handler, there’s no way to get rid of it. When you restart the game the old event handlers are still hanging out in the background and new event handlers are created, which is why you see it changing by 2 instead of one.

As a rule, you should never put an onEvent() block inside another block in order to prevent duplicating your event handlers. One approach to getting the kind of behavior your student is looking for would be to create a single event handler at the top level for each of “dogclicker” and “catclicker” and then use a variable to track whether you have chosen dog or cat mode. This could roughly look like this:

var target = "dogclicker";

onEvent("dogclicker", "click", function() {
  if (target == "dogclicker") {
    score = score + 1;
  } else {
    lives = lives - 1;
  }
}

onEvent("catclicker", "click", function() {
  if (target == "catclicker") {
    score = score + 1;
  } else {
    lives = lives - 1;
  }
}
2 Likes