Counter
In this chapter, we introduce event handlers. Take a look at this demo, with plus and minus buttons that increment and decrement a counter. You may remember it from the pupy.dev homepage.
In this example, we bind two events to event handlers. Follow along with the annotations in the code below for a more detailed explanation:
- The
on_click
parameter is passed to thebutton
tag, which binds theon_decrement_click
method to the button's click event. - The
on_click
parameter is passed to thebutton
tag, which binds theon_increment_click
method to the button's click event. - The
on_decrement_click
method decrements thecurrent_value
key in the page's state. - The
on_increment_click
method increments thecurrent_value
key in the page's state.
Tip
The event
parameter sent to event handlers is the same as it is in JavaScript. You can call event.preventDefault()
or event.stopPropagation()
as needed.
As before, because we are modifying the state directly, the page will re-render automatically. This is the power of PuePy's reactivity system.