You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 2-ui/2-events/4-bubbling-and-capturing/article.md
+17-20Lines changed: 17 additions & 20 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -50,7 +50,7 @@ The process is called "bubbling", because events "bubble" from the inner element
50
50
```warn header="*Almost* all events bubble."
51
51
The key word in this phrase is "almost".
52
52
53
-
For instance, a `focus` event does not bubble. There are other examples too. But still it's an exception, rather then a rule, most events do bubble.
53
+
For instance, a `focus` event does not bubble. There are other examples too, we'll meet them. But still it's an exception, rather then a rule, most events do bubble.
54
54
```
55
55
56
56
## event.target
@@ -135,14 +135,14 @@ That is: for a click on `<td>` the event first goes through the ancestors chain
135
135
136
136
**Before we only talked about bubbling, because the capturing stage is rarely used. Normally it is invisible to us.**
137
137
138
-
Handlers added using `on...`-property or using HTML attributes don't know anything about capturing, they only work at the bubbling stage.
138
+
Handlers added using `on...`-property or using HTML attributes don't know anything about capturing, they only run on the 2nd and 3rd stages.
139
139
140
140
To catch an event on the capturing stage, we need to use the 3rd argument of `addEventListener`:
141
141
142
142
- If it's `true`, then the handler is set on the capturing stage.
143
143
- If it's `false` (default), then on the bubbling stage.
144
144
145
-
Formally, there are 3 stages, but the stage `2`(reached the element) has no special processing, because handlers on both capturing and bubbling stages run on the element itself.
145
+
Note that while formally there are 3 stages, the 2nd stage (reached the element) is not handled separately: handlers on both capturing and bubbling stages do that.
146
146
147
147
Let's see it in action:
148
148
@@ -174,29 +174,26 @@ Please note that `TD` shows up two times: at the end of capturing and at the sta
174
174
175
175
There's a property `event.eventPhrase` that tells us the number of the stage on which the event was caught. But it's rarely used, because we usually know it in the handler.
176
176
177
-
## TODO: ADD DELEGATION HERE
177
+
## Summary
178
178
179
-
## Итого
179
+
The event handling process:
180
180
181
-
Алгоритм:
181
+
- When an event happens -- the most nested element where it happens gets labeled as the "source element" (`event.target`).
182
+
- Then the event first moves from the document root down the `event.target`, calling handlers assigned with `addEventListener(...., true)` on the way.
183
+
- Then the event moves from `event.target` up to the root, calling handlers assigned using `on*` and `addEventListener(...., false)`.
182
184
183
-
- При наступлении события -- элемент, на котором оно произошло, помечается как "целевой" (`event.target`).
184
-
- Далее событие сначала двигается вниз от корня документа к `event.target`, по пути вызывая обработчики, поставленные через `addEventListener(...., true)`.
185
-
- Далее событие двигается от `event.target` вверх к корню документа, по пути вызывая обработчики, поставленные через `on*` и `addEventListener(...., false)`.
185
+
Each handler can access `event` object properties:
186
186
187
-
Каждый обработчик имеет доступ к свойствам события:
187
+
-`event.target` -- the deepest element that originated the event.
188
+
-`event.currentTarget` (=`this`) -- the current element the handles the event (the one that has the handler on it)
189
+
-`event.eventPhase` -- the current phase (capturing=1, bubbling=3).
188
190
189
-
-`event.target` -- самый глубокий элемент, на котором произошло событие.
190
-
-`event.currentTarget` (=`this`) -- элемент, на котором в данный момент сработал обработчик (до которого "доплыло" событие).
191
-
-`event.eventPhase` -- на какой фазе он сработал (погружение =1, всплытие = 3).
191
+
Any event handler can stop the event by calling `event.stopPropagation()`, but that's not recommended, because we can't really be sure we won't need it, maybe for completely different things.
192
192
193
-
Любой обработчик может остановить событие вызовом `event.stopPropagation()`, но делать это не рекомендуется, так как в дальнейшем это событие может понадобиться, иногда для самых неожиданных вещей.
193
+
The capturing stage is used very rarely, usually we handle events on bubbling. And there's a logic behind that.
194
194
195
-
В современной разработке стадия погружения используется очень редко.
195
+
In real world, when an accident happens, local authorities react first. They know best the area where it happened. Then (if needed) higher-level powers, and so on.
196
196
197
-
Этому есть две причины:
197
+
The same for event handlers. The code that set the handler on a particular element knows maximum details about the element and what it does. A handler on a particular `<td>` may be suited for that exactly `<td>`, it knows everything about it, so it should get the chance first. Then its immediate parent also knows about the context, but a little bit less, and so on till the very top element that handles general concepts and runs the last.
198
198
199
-
1. Историческая -- так как IE лишь с версии 9 в полной мере поддерживает современный стандарт.
200
-
2. Разумная -- когда происходит событие, то разумно дать возможность первому сработать обработчику на самом элементе, поскольку он наиболее конкретен. Код, который поставил обработчик именно на этот элемент, знает максимум деталей о том, что это за элемент, чем он занимается.
201
-
202
-
Далее имеет смысл передать обработку события родителю -- он тоже понимает, что происходит, но уже менее детально, далее -- выше, и так далее, до самого объекта `document`, обработчик на котором реализовывает самую общую функциональность уровня документа.
199
+
Bubbling and capturing lay the foundation for "event delegation" -- an extremely powerful event handling pattern that we study in the next chapter.
0 commit comments