Event Handling Basics
By the end of this lesson, you'll be able to:
- Attach a click or change event handler in a template
- Write a corresponding handler method in the JavaScript class
- Read details off the event object inside a handler
Prerequisites: "Conditional and List Rendering"
Attaching an Event Listener
<lightning-button label="Save" onclick={handleSave}></lightning-button>
Note the binding is {handleSave} — a reference to the method, not {handleSave()}, which would call it immediately at render time instead of when the button is actually clicked. This is one of the most common first bugs in LWC.
Writing the Handler
handleSave(event) {
console.log('Save clicked');
}
Inside a handler, this correctly refers to the component instance — LWC automatically binds template-referenced handler methods for you, so you don't need the arrow-function workarounds sometimes seen in other JavaScript contexts.
Reading Event Details
handleNameChange(event) {
this.currentValue = event.target.value;
}
event.target is the element that triggered the event; for form-style elements, event.target.value holds the current input value — the full pattern for building forms is covered in Module 8.
Why This Matters in Real Projects
Virtually every interactive component depends on event handling in some form. It's also the exact foundation Module 5 builds on for cross-component communication — a child component notifying its parent works through the same on{eventName} pattern used here for standard DOM events.
Exercise
Spot the bug: onclick={handleSave()} — explain what's wrong and how to fix it.
Show hint
Compare a method reference to a method call.
Exercise
Challenge: write a handler method readValue(event) that stores event.target.value into a class field called typedText.
Show hint
Assign directly inside the method body.
Event Handling Basics Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Event handling is the foundation every interactive component depends on — and the exact same on{eventName} pattern used for standard DOM events is reused later for custom component-to-component events.