Programming with Callbacks
Don't call us, we'll call you
Daniel Jackson
Callbacks
- APIs: using objects through specs
- Callbacks: functions that an object calls
- Registration methods
A Traffic light API
- To use an object, you just need specs of methods: the API
- API for traffic light:
- red: switch to red light
- yellow: switch to yellow light
- green: switch to green light
- next: switch to next light in sequence
- Can you turn the light to green?
- Can you cycle through the colors on each click of run?
Answer: A Traffic light API
- Easy: just use the green method, and click run
- Then replace all the code by t.next() and click run
Don't call me, I'll call you
- We've seen that functions can be passed as arguments
- Callback or listener: function passed as argument, called later
- Example: account that lets you choose how success is reported
Traffic Light in the Bank
- Let's hook the account up to the traffic light
- Recall that t.green if a function that turns t green
- Can you change the withdrawal amount so that a red light shows?
- Can you make it show yellow for a failed account operation?
Answer: Traffic Light in the Bank
- To show yellow for failed account operation, just pass t.yellow instead
On the Button
- Often want to choose the callback dynamically
- Common idiom: provide a registration method
- Our button object has method onclick(f) to register f for clicks
- Run the code, and click the button to see what happens
Answer: Controlling the Lights
- The call to onclick binds the function t.next to the button
- Now every time the button is clicked, the traffic light switches to next color
Exercise: Action & Reaction
- Build a reaction tester
- Should go green after random delay
- Then you click button, and it reports your reaction time
- Hint: now() returns current time in ms
Answer: Action & Reaction
Some Functions
- Functions for the next exercise
Exercise: Action & Reaction Trace
- This time, compute average over multiple tries
- Complete the code inside the function report
- Hint: use some of map, reduce, zip, filter and pos, plus, max
Solution: Action & Reaction Trace