Defining functions with an event listener inside?! Does this follow good programming practices?!

This year, I’ve had a number of students come up with a clever solution for dealing with certain buttons that need to do the same things over and over. What they’ve done is defined a function that took parameters, and then called this function with the parameters necessary to create onEvents (event listeners)

As you can see in the following project, the student created a buttonChangeScreen function line 109 simply to switch screens. The function is called on lines 23, 24, 25, then again on 42, 43.

[App Lab -]

The answers to the quiz are: Q1) Carbon, Q2) Sulfur

My question is - is this good programming practice?! It doesn’t seem like it’s really “event driven” programming… it’s more like sequential programming before anything else!

I’m a little behind on looking at my formative assessments, and students are working on a bigger summative project now. Not sure whether to let this fly.

Thanks in advance!

In my opinion, onEvents should be independent and not be placed inside functions since onEvents are triggered by events and functions may be called within onEvents or outside of onEvents.

1 Like

Yes, this is fine. There is no danger of going rogue the way it is used. They have added an additional abstraction to the already abstracted onEvent().

Fortunately, App Lab is based on Javascript.

function buttonChangeScreen(button,Screen){

The innermost function definition creates something called a closure. It is an advanced concept, but here it makes the whole thing work correctly. See also Programming Concept onEvent, Functions and Event handlers, OnEvents as Functions then Functions inside of Functions. If your students have found this it is time to talk about closures.