Calling Back When Something Happens
This lesson ports two callbacks: the class’s full-up warning and its end-of-class reminder. The
Learn to Boulder class has two places. Python’s make_session() takes an optional callback
for when it fills, on_full, None by default, and checks that one was passed before calling it
with the class’s name:
def make_session(
name,
prefix,
places,
on_full=None,
):
climbers = []
def check_in(climber):
climbers.append(climber)
if len(climbers) == places and on_full is not None:
on_full(name)
return f"{prefix}-{100 + len(climbers)} {climber}"
return check_in
def announce_full(name):
print(f"{name} is full")
intro = make_session(
"Learn to Boulder", "L", 2, on_full=announce_full
)
print(intro("Mia Novak"))
print(intro("Leo Park"))
Run it for Mia and Leo, and Leo’s warning comes before his wristband. What does JavaScript do instead of that check?
In JavaScript, the factory ports line by line, with camelCase names, returning the check-in as an
arrow. The list becomes an array, and the f-string a template literal. The callback becomes a short
arrow, as small functions usually are. With no keyword arguments, it travels in an options object,
keyed by name: onFull. The last two lines log the wristbands.
Where Python defaults to None, JavaScript usually gives an optional callback a do-nothing
default: an arrow with an empty body, () => {}. The outer braces pull onFull out of the options
object, and the = {} after them covers a call without one. So the check drops out: