liveBook · Manning

Handler

As explained in Web Components in Action

An event listener is a callback registration that causes code to run when a specified event occurs on an object.

An event handler is a callback that runs when a specified event occurs on an object. Register one with addEventListener to connect user input to component behavior. section 2.6 section 5.3

Listing 2.12. Adding click listeners to our buttons
. . .'<button class="back">&lt</button>' +
       '<button class="forward">&gt</button>';

this.showPhoto();

this.querySelector('button.back').addEventListener('click', event =>
     this.onBackButtonClick(event));                                     #1

this.querySelector('button.forward').addEventListener('click', event =>
     this.onForwardButtonClick(event));                                  #2

}

This carousel registers click handlers on its back and forward buttons, passing each event to a component method. section 2.6

Handlers can respond to different kinds of input:

  • Carousel button handlers advance or rewind the photo index, then display the selected photo. section 2.6
  • A slider routes mouse-down, mouse-up, and mouse-move events through a handler to manage dragging and update its value. section 3.6
  • A mouse-move handler passes current and previous coordinates to a child component to determine which harp string was strummed. section 5.3

Arrow-function callbacks preserve access to the component instance, allowing handlers to call its methods and use its properties. section 2.6 section 5.3

How Web Components in Action covers it

How deep it goes
Demonstrates listener registration, callback scope, and event-driven component behavior without surveying the event API.
Examples
Uses photo-carousel buttons, a draggable slider, and mouse-strummed harp strings as concrete event-driven examples.
What you can do after
Apply it via addEventListener to route click or mouse events into component methods.
How it connects
Connects event handlers to callbacks, the DOM, Web Components, and mouse events.

Also explained in

Compare how 22 books explain handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.