An arrow function is a JavaScript function expression written with =>. Its key practical benefit here is preserving the surrounding class instance as this when an event callback runs. section 2.6 section 1.1
Use an arrow function when a component callback needs to keep access to its instance:
- Register a button listener with event => this.onBackButtonClick(event), allowing the handler to use component properties and methods. section 2.6
- Register mouse movement with e => this.onMouseMove(e), preserving the class scope while forwarding the event to a method. section 5.3
- Use an arrow function inside setTimeout when the delayed callback must call another method on the same component. section 5.3
Keeping a carousel callback connected to its component
this.querySelector('button.forward').addEventListener('click', event => this.onForwardButtonClick(event)); The arrow callback forwards the click event while retaining the component instance, so onForwardButtonClick can update _photoIndex and call showPhoto(). section 2.6
Listing 5.11. Adding an event listener with the fat arrow
// file: components/app/app.js
connectedCallback() {
this.innerHTML = '<webharp-strings strings="' +
this.getAttribute('strings') + '"></webharp-strings>';
this.stringsElement = #1
this.querySelector('webharp-strings');
this.addEventListener('mousemove', #2
e => this.onMouseMove(e));
}
Inspect the complete event-listener example, including the arrow callback and the connected Web Harp mouse-move handler. section 5.3






