Forestil dig dette scenarie:
Du bygger en liste over brugere. Du viser deres navne, yndlingsfarver og e-mails. Når du klikker på en bruger (en række i tabellen), vil du have det til at føre dig til brugeroptegnelsen. Bortset fra når du klikker på e-mail, skal den åbne en e-mail-dialog.
Du skriver muligvis en kode som denne (vi bruger en tabel her, fordi den er let at forstå - selvom vi selvfølgelig måske bruger noget meget mere kompliceret i vores projekt):
Name Colors Susie Blue, Red [email protected]
Hvis du vil klikke på en af disse rækker, tilføjer du sandsynligvis en
onClickfunktion til rækken. På den måde, hvis de klikker et vilkårligt sted i rækken, kan de gå direkte til brugeroptegnelsen.
For at tage os af e-mailen laver vi en
ef> tag on the text.
Event propagation is a way to describe the “stack” of events that are fired in a web browser. In our table example above, clicking on the
a tag is the first event that we will fire, but there are other events too.
To understand that concept, you must understand that the elements on a web browser are nested. They do not cover each other up. So a click on the
a tag also clicks on the row, the table, the
div in which the table is nested, and anything else all the way out to
document , the complete container that holds everything in your browser.
If we’ve put any other
onClick events inside of these other elements, they will also be fired when we click on the
a link in the table. That’s why we will be directed to the user record when we click on the email link. It’s going to perform both the
onClick function for the
a link and the
onClick function for the row.
The movement of events “up” from the most-nested element (
a) out to the least-nested (
document) is referred to as “bubbling.” If events start in the “outer-most” element and moved “down,” that is referred to as “trickling.” All you probably care about is the default behavior: bubbling.
Honestly, I hadn’t run into any use-case for caring about event propagation until this week, when I needed to build a table with a checkbox in it. Unfortunately for me, when I tried to set up the checking functionality, it took me to the record. Fortunately, I did some training earlier (see references below) that gave me a clue on exactly what I had to Google.
You may be thinking: why not just use
e.preventDefault()? That is indeed the first thing I tried, but there simply is no default behavior for a span (unlike a form, whose default submit behavior will refresh the page).
- This Stack Overflow answer, which nicely sums up some of the more nuanced bits of event capture and propagation.