Skip to content

Commit 25b7c2e

Browse files
committed
delegation
1 parent e62004a commit 25b7c2e

19 files changed

Lines changed: 180 additions & 148 deletions

File tree

2-ui/2-events/4-event-bubbling/article.md renamed to 2-ui/2-events/4-bubbling-and-capturing/article.md

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ The process is called "bubbling", because events "bubble" from the inner element
5050
```warn header="*Almost* all events bubble."
5151
The key word in this phrase is "almost".
5252
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.
5454
```
5555

5656
## event.target
@@ -135,14 +135,14 @@ That is: for a click on `<td>` the event first goes through the ancestors chain
135135

136136
**Before we only talked about bubbling, because the capturing stage is rarely used. Normally it is invisible to us.**
137137

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.
139139

140140
To catch an event on the capturing stage, we need to use the 3rd argument of `addEventListener`:
141141

142142
- If it's `true`, then the handler is set on the capturing stage.
143143
- If it's `false` (default), then on the bubbling stage.
144144

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.
146146

147147
Let's see it in action:
148148

@@ -174,29 +174,26 @@ Please note that `TD` shows up two times: at the end of capturing and at the sta
174174

175175
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.
176176

177-
## TODO: ADD DELEGATION HERE
177+
## Summary
178178

179-
## Итого
179+
The event handling process:
180180

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)`.
182184

183-
- При наступлении события -- элемент, на котором оно произошло, помечается как "целевой" (`event.target`).
184-
- Далее событие сначала двигается вниз от корня документа к `event.target`, по пути вызывая обработчики, поставленные через `addEventListener(...., true)`.
185-
- Далее событие двигается от `event.target` вверх к корню документа, по пути вызывая обработчики, поставленные через `on*` и `addEventListener(...., false)`.
185+
Each handler can access `event` object properties:
186186

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).
188190

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.
192192

193-
Любой обработчик может остановить событие вызовом `event.stopPropagation()`, но делать это не рекомендуется, так как в дальнейшем это событие может понадобиться, иногда для самых неожиданных вещей.
193+
The capturing stage is used very rarely, usually we handle events on bubbling. And there's a logic behind that.
194194

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.
196196

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.
198198

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.

2-ui/2-events/4-event-bubbling/both.view/example.css renamed to 2-ui/2-events/4-bubbling-and-capturing/both.view/example.css

File renamed without changes.

2-ui/2-events/4-event-bubbling/both.view/index.html renamed to 2-ui/2-events/4-bubbling-and-capturing/both.view/index.html

File renamed without changes.

2-ui/2-events/4-event-bubbling/both.view/script.js renamed to 2-ui/2-events/4-bubbling-and-capturing/both.view/script.js

File renamed without changes.

2-ui/2-events/4-event-bubbling/bubble-target.view/example.css renamed to 2-ui/2-events/4-bubbling-and-capturing/bubble-target.view/example.css

File renamed without changes.

2-ui/2-events/4-event-bubbling/bubble-target.view/index.html renamed to 2-ui/2-events/4-bubbling-and-capturing/bubble-target.view/index.html

File renamed without changes.

2-ui/2-events/4-event-bubbling/bubble-target.view/script.js renamed to 2-ui/2-events/4-bubbling-and-capturing/bubble-target.view/script.js

File renamed without changes.

2-ui/2-events/4-event-bubbling/capture.view/example.css renamed to 2-ui/2-events/4-bubbling-and-capturing/capture.view/example.css

File renamed without changes.

2-ui/2-events/4-event-bubbling/capture.view/index.html renamed to 2-ui/2-events/4-bubbling-and-capturing/capture.view/index.html

File renamed without changes.

2-ui/2-events/4-event-bubbling/capture.view/script.js renamed to 2-ui/2-events/4-bubbling-and-capturing/capture.view/script.js

File renamed without changes.

0 commit comments

Comments
 (0)