Callbacks and Event Listeners

Homework

  1. Variable Handling
  2. Callback Functions
  3. Events and Listeners

Morning reflection

Housekeeping

  • Volunteers: function mentors

1. Demo: Tip Calculator

Learning Objectives

Materials

Key Takeaways

  • The key goal is to fail gracefully and (among other things) avoid printing/using a variable that is undefined, null or empty.
  • Use ??= to allow zero (0) as a value for arithmetic functions.

Activities

  1. Research:
    • How to test for an empty array?
    • How to test for an empty object?
    • How do utility libraries like Lodash or underscore test for emptiness?
  2. Find a personal project, assignment or class example and try to break it with empty/falsy/null/undefined values. What’s the best method for fixing them?

2. Callback functions

Learning Objectives

  1. Understand the difference between invoking a function and passing a function as a value.
  2. Define callback function.
  3. Define anonymous function.
  4. Create a greet function that accepts a function as a parameter.
  5. Pass an anonymous callback function using a function expression.

Terminology

Callback Function
A function passed to another function, presumably to be invoked later.
Anonymous Function
A function expression passed as a value with no name. This is how callback functions are often created.

Materials

Key Takeaways

  • The callback function is a general programming pattern that’s possible with first-class functions. There are many use cases in JS such as event emitters, array/object sorting, looping, etc.
  • If a function is only passed as a value once in your code, it’s often better to pass it as an anonymous function so that your code is in the same lexical location.

Activities

  1. Try stepping into the callback functions using the VS Code Debug panel. Let Tony know if you can get it work (or not).

3. Handling events and event objects

Learning Objectives

  • Discuss Javascript events in terms of callback functions.
  • Log an event object to the console and inspect it.
  • Discuss event capturing and bubbling.

Materials

Activities

  1. Log different event objects to the console and inspect them.
    • How are the events triggered?
    • What are common properties and methods common to each event? Which are different?
  2. Integrate an event you’ve never used before into a project. For example, can you modify a CSS Variable with the scroll wheel?
  3. Advanced: Using a personal project, assignment or class example, try capturing click (or similar) event from the target’s container.

Lab-time!

  1. See the activities above
  2. Assignments and readings
  3. Experiments for the portfolio

Tony’s goals for Lab-Time

  • Convert tip calculator starter and finished to Gist
  • Create Gist for falsy/null/undefined testing

Dailies

  • Submit today’s Codepen/repo/gist to the Dailies section (in Assessments) in Brightspace.