Single event linked to multiple IDs?

Is it possible to link a single event to multiple IDs? Is there a direct way to do this without creating functions?

@smitchell2 I do not believe that is possible. Each event needs a function to execute the event.

That’s what I thought. Good to have confirmation.

Hi,

I have been experimenting with a school timetable app in App Lab and have linked 50 buttons (with ids of 1, 2, 3, etc.) to one function using a simple for loop and the event.srcElementId attribute which can be used to identify which button was clicked.

So even though you can’t have a single event linked to multiple IDs directly, you can have multiple events calling the same function with a different parameter. I have pasted some of my code below. Hope this is helpful.

Question: For some reason when I use the variable i instead of event.srcElementId, it doesn’t seem to work correctly, and the scheduleClass function logs the number 51, regardless of what button is pressed. Is someone able to explain why that is happening?

function scheduleClass(timeslot) {
   console.log(timeslot);
}

for (var i=1;i<=50;i++) {
    onEvent(i, "click", function(event) {
      scheduleClass(event.srcElementId);
  });
}

The reason using i alone doesn’t work is because when the time comes to run scheduleClass(i) it’s looking up the current value of i, which after the loop has finished running will be 51. event.srcElementId on the other hand is coming from the event handlers event parameter, so it’s certain to be current.

It’s worth pointing out that there actually is a way to make a single event handler respond to multiple buttons though, using that same event parameter. If you attach an event handler to the screen, then it will capture all clicks on the screen. Then from the event variable to can determine which element on the screen was clicked and respond accordingly. eg https://studio.code.org/projects/applab/2N_57u-u48BGKuOi9jkQ7A/edit

for (var i = 0; i < 50; i++) {
  button("id" + i, "text");
}

onEvent("screen1", "click", function(event) {
  var elementClicked = event.targetId;
  if (elementClicked != "screen1") {
    scheduleClass(elementClicked);
  }
});

function scheduleClass(timeslot) {
   console.log(timeslot);
}

Thank you for posting this - very elegant. Great example that can be extended for all sorts of interesting things for students - thinking of game “Deal or No Deal” or even creating MineSweep type game.