Event Bubbling

Demo

Key pressed:

HTML #

 1<div id="demo">
 2    Key pressed: <span data-text="$key"></span>
 3    <div id="button-container" data-on-click="$key = evt.target.dataset.id">
 4        <button data-id="KEY ELSE" class="gray">KEY<br/>ELSE</button>
 5        <button data-id="CM">CM</button>
 6        <button data-id="OM">OM</button>
 7        <button data-id="FETCH">FETCH</button>
 8        <button data-id="SET">SET</button>
 9        <button data-id="EXEC">EXEC</button>
10        <button data-id="TEST ALARM" class="gray">TEST<br/>ALARM</button>
11        <button data-id="3">3</button>
12        <button data-id="2">2</button>
13        <button data-id="1">1</button>
14        <button data-id="ENTER">ENTER</button>
15        <button data-id="CLEAR">CLEAR</button>
16    </div>
17</div>
18
19<style>
20    #button-container {
21        pointer-events: none;
22    }
23</style>

Explanation #

This example shows how event bubbling can be leveraged using Datastar. A data-on-click attribute on the parent container of the buttons. When any button is clicked, the event bubbles up to the parent, where we can access the clicked button’s data-id attribute via evt.target.dataset.id. This allows us to handle all button clicks with a single event listener.

Note the pointer-events: none; style on the button container. This is to prevent the container from sending click events.