@@ -189,38 +189,38 @@ Any handler can listen for that event with `rabbit.addEventListener('hide',...)` ``` -Please note: the event must have the flag `cancelable: true`, otherwise the call `event.preventDefault()` is ignored. +Зверніть увагу: подія повинна мати прапор `cancelable: true`, інакше виклик `event.preventDefault()` ігнорується. -## Events-in-events are synchronous +## Вкладені події є синхронними -Usually events are processed in a queue. That is: if the browser is processing `onclick` and a new event occurs, e.g. mouse moved, then it's handling is queued up, corresponding `mousemove` handlers will be called after `onclick` processing is finished. +Як правило, події обробляються в черзі. Тобто: якщо браузер обробляє `onclick` і відбувається нова подія, напр. курсор було переміщено, тоді її обробка ставиться в чергу, відповідні обробники `mousemove` будуть викликані після завершення обробки `onclick`. -The notable exception is when one event is initiated from within another one, e.g. using `dispatchEvent`. Such events are processed immediately: the new event handlers are called, and then the current event handling is resumed. +Винятком є випадки, коли одна подія починається з іншої, напр. використовуючи `dispatchEvent`. Такі події обробляються негайно: викликаються нові обробники подій, а потім відновлюється обробка поточної події. -For instance, in the code below the `menu-open` event is triggered during the `onclick`. +Наприклад, у коді нижче подія `menu-open` ініціюється під час `onclick`. -It's processed immediately, without waiting for `onclick` handler to end: +Вона обробляється негайно, не чекаючи закінчення обробки `onclick`: ```html run autorun - + ``` -The output order is: 1 -> nested -> 2. +Порядок виведення такий: 1 -> вкладена подія -> 2. -Please note that the nested event `menu-open` is caught on the `document`. The propagation and handling of the nested event is finished before the processing gets back to the outer code (`onclick`). +Зауважте, що вкладена подія `menu-open` ловиться на `document`. Поширення та обробка вкладеної події закінчується до того, як опрацювання повернеться до зовнішнього коду (`onclick`). -That's not only about `dispatchEvent`, there are other cases. If an event handler calls methods that trigger other events -- they are processed synchronously too, in a nested fashion. +Це стосується не тільки `dispatchEvent`, є й інші випадки. Якщо обробник подій викликає методи, які викликають інші події, вони також обробляються синхронно, вкладеним способом. -Let's say we don't like it. We'd want `onclick` to be fully processed first, independently from `menu-open` or any other nested events. +Скажімо, нам це не подобається. Ми б хотіли спочатку повністю обробити `onclick`, незалежно від `menu-open` або будь-яких інших вкладених подій. -Then we can either put the `dispatchEvent` (or another event-triggering call) at the end of `onclick` or, maybe better, wrap it in the zero-delay `setTimeout`: +Тоді ми можемо або помістити `dispatchEvent` (або інший виклик, що ініціює подію) в кінець `onclick`, або, можливо, краще, загорнути його в `setTimeout` з нульовою затримкою: ```html run - + ``` -Now `dispatchEvent` runs asynchronously after the current code execution is finished, including `menu.onclick`, so event handlers are totally separate. +Тепер `dispatchEvent` запускається асинхронно після завершення поточного виконання коду, включаючи `menu.onclick`, тому обробники подій повністю відокремлені. -The output order becomes: 1 -> 2 -> nested. +Порядок виведення стає: 1 -> 2 -> вкладена подія. -## Summary +## Підсумки -To generate an event from code, we first need to create an event object. +Щоб створити подію з коду, нам спочатку потрібно створити об’єкт події. -The generic `Event(name, options)` constructor accepts an arbitrary event name and the `options` object with two properties: -- `bubbles: true` if the event should bubble. -- `cancelable: true` if the `event.preventDefault()` should work. +Базовий конструктор `Event(name, options)` приймає довільне ім’я події та об’єкт параметрів із двома властивостями: +- `bubbles: true` якщо подія має спливати. +- `cancelable: true` якщо `event.preventDefault()` повинен працювати. -Other constructors of native events like `MouseEvent`, `KeyboardEvent` and so on accept properties specific to that event type. For instance, `clientX` for mouse events. +Інші конструктори вбудованих подій, як-от `MouseEvent`, `KeyboardEvent` тощо, приймають властивості, характерні для цього типу події. Наприклад, `clientX` для подій миші. -For custom events we should use `CustomEvent` constructor. It has an additional option named `detail`, we should assign the event-specific data to it. Then all handlers can access it as `event.detail`. +Для користувацьких подій ми повинні використовувати конструктор `CustomEvent`. Він має додаткову опцію з назвою `detail`, ми повинні призначити їй дані, що стосуються події. Тоді всі обробники зможуть отримати до них доступ як `event.detail`. -Despite the technical possibility of generating browser events like `click` or `keydown`, we should use them with great care. +Незважаючи на технічну можливість генерування подій браузера, таких як `click` або `keydown`, ми повинні користуватись цим з великою обережністю. -We shouldn't generate browser events as it's a hacky way to run handlers. That's bad architecture most of the time. +Ми не повинні генерувати події браузера, оскільки це хакерський спосіб запуску обробників. Найчастіше це ознака поганої архітектура. -Native events might be generated: +Вбудовані події можуть бути створені: -- As a dirty hack to make 3rd-party libraries work the needed way, if they don't provide other means of interaction. -- For automated testing, to "click the button" in the script and see if the interface reacts correctly. +- Як явний хак, щоб змусити сторонні бібліотеки працювати належним чином, якщо вони не забезпечують інших засобів взаємодії. +- Для автоматизованого тестування, щоб "клікнути кнопку" в скрипті та перевірити, чи правильно реагує інтерфейс. -Custom events with our own names are often generated for architectural purposes, to signal what happens inside our menus, sliders, carousels etc. +Користувацькі події з нашими власними назвами найчастіше генеруються для архітектурних цілей, щоб сигналізувати про те, що відбувається в наших меню, повзунках, каруселях тощо.pFad - Phonifier reborn Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: