alert will trigger immediately.
+ Tuto funkcionalitu podporuje většina moderních prohlížečů. Po provedení těchto akcí se okamžitě spustí alert.
## FinalizationRegistry
-Now it is time to talk about finalizers. Before we move on, let's clarify the terminology:
+Nyní nastal čas pohovořit o finalizátorech. Než budeme pokračovat, ujasníme si terminologii:
-**Cleanup callback (finalizer)** - is a function that is executed, when an object, registered in the `FinalizationRegistry`, is deleted from memory by the garbage collector.
+**Úklidový callback (finalizátor)** - je funkce, která je spuštěna, když je objekt registrovaný ve `FinalizationRegistry` odstraněn z paměti sběračem odpadků.
-Its purpose - is to provide the ability to perform additional operations, related to the object, after it has been finally deleted from memory.
+Jejím účelem je poskytnout možnost provést další operace vztahující se k objektu poté, co byl definitivně odstraněn z paměti.
-**Registry** (or `FinalizationRegistry`) - is a special object in JavaScript that manages the registration and unregistration of objects and their cleanup callbacks.
+**Registr** (nebo `FinalizationRegistry`) - je speciální objekt v JavaScriptu, který spravuje registraci a deregistraci objektů a jejich úklidových callbacků.
-This mechanism allows registering an object to track and associate a cleanup callback with it.
-Essentially it is a structure that stores information about registered objects and their cleanup callbacks, and then automatically invokes those callbacks when the objects are deleted from memory.
+Tento mechanismus umožňuje registrovat objekt ke sledování a připojit k němu úklidový callback.
+V zásadě je to struktura, která ukládá informace o registrovaných objektech a jejich úklidových callbaccích a pak, když jsou objekty odstraněny z paměti, tyto callbacky automaticky vyvolává.
-To create an instance of the `FinalizationRegistry`, it needs to call its constructor, which takes a single argument - the cleanup callback (finalizer).
+Abychom vytvořili instanci třídy `FinalizationRegistry`, musíme volat její konstruktor, který obsahuje jediný argument - úklidový callback (finalizátor).
-Syntax:
+Syntaxe:
```js
-function cleanupCallback(heldValue) {
- // cleanup callback code
+function úklidovýCallback(uchovávanáHodnota) {
+ // kód úklidového callbacku
}
-const registry = new FinalizationRegistry(cleanupCallback);
+const registr = new FinalizationRegistry(úklidovýCallback);
```
-Here:
-
-- `cleanupCallback` - a cleanup callback that will be automatically called when a registered object is deleted from memory.
-- `heldValue` - the value that is passed as an argument to the cleanup callback. If `heldValue` is an object, the registry keeps a strong reference to it.
-- `registry` - an instance of `FinalizationRegistry`.
+Zde:
-`FinalizationRegistry` methods:
+- `úklidovýCallback` - úklidový callback, který bude automaticky zavolán, až bude registrovaný objekt odstraněn z paměti.
+- `uchovávanáHodnota` - hodnota, která je předána úklidovému callbacku jako argument. Pokud `uchovávanáHodnota` je objekt, registr si na něj uchovává silný odkaz.
+- `registr` - instance třídy `FinalizationRegistry`.
-- `register(target, heldValue [, unregisterToken])` - used to register objects in the registry.
+Metody třídy `FinalizationRegistry`:
- `target` - the object being registered for tracking. If the `target` is garbage collected, the cleanup callback will be called with `heldValue` as its argument.
+- `register(cíl, uchovávanáHodnota [, registračníZnámka])` - používá se k registraci objektů v registru.
- Optional `unregisterToken` – an unregistration token. It can be passed to unregister an object before the garbage collector deletes it. Typically, the `target` object is used as `unregisterToken`, which is the standard practice.
-- `unregister(unregisterToken)` - the `unregister` method is used to unregister an object from the registry. It takes one argument - `unregisterToken` (the unregister token that was obtained when registering the object).
+ `cíl` - objekt registrovaný pro sledování. Pokud je `cíl` odstraněn sběračem odpadků, bude zavolán úklidový callback s argumentem `uchovávanáHodnota`.
+
+ Nepovinná `registračníZnámka` – známka pro zrušení registrace. Můžeme ji předat, abychom mohli registraci objektu zrušit ještě dříve, než jej sběrač odpadků odstraní. Zpravidla se jako `registračníZnámka` používá objekt `cíl`, což je standardní praktika.
+- `unregister(registračníZnámka)` - metoda `unregister` se používá ke zrušení registrace objektu v registru. Obsahuje jeden argument - `registračníZnámka` (známka pro zrušení registrace, která byla zadána při registraci objektu).
-Now let's move on to a simple example. Let's use the already-known `user` object and create an instance of `FinalizationRegistry`:
+Přejděme nyní k jednoduchému příkladu. Využijme již známý objekt `uživatel` a vytvořme instanci třídy `FinalizationRegistry`:
```js
-let user = { name: "John" };
+let uživatel = { jméno: "Jan" };
-const registry = new FinalizationRegistry((heldValue) => {
- console.log(`${heldValue} has been collected by the garbage collector.`);
+const registr = new FinalizationRegistry((uchovávanáHodnota) => {
+ console.log(`${uchovávanáHodnota} byl odstraněn sběračem odpadků.`);
});
```
-Then, we will register the object, that requires a cleanup callback by calling the `register` method:
+Pak objekt, pro který požadujeme úklidový callback, zaregistrujeme voláním metody `register`:
```js
-registry.register(user, user.name);
+registr.register(uživatel, uživatel.jméno);
```
-The registry does not keep a strong reference to the object being registered, as this would defeat its purpose. If the registry kept a strong reference, then the object would never be garbage collected.
+Registr si na registrovaný objekt neuchovává silný odkaz, protože by tím ztratil smysl. Kdyby si jej uchovával, objekt by nikdy nebyl sběračem odpadků odklizen.
-If the object is deleted by the garbage collector, our cleanup callback may be called at some point in the future, with the `heldValue` passed to it:
+Jestliže objekt bude odklizen sběračem odpadků, může být někdy v budoucnu zavolán náš úklidový callback, kterému se předá `uchovávanáHodnota`:
```js
-// When the user object is deleted by the garbage collector, the following message will be printed in the console:
-"John has been collected by the garbage collector."
+// Když je objekt uživatel odklizen sběračem odpadků, vypíše se na konzoli následující zpráva:
+"Jan byl odstraněn sběračem odpadků."
```
-There are also situations where, even in implementations that use a cleanup callback, there is a chance that it will not be called.
+Existují však situace, v nichž se i v implementacích využívajících úklidový callback může stát, že úklidový callback nebude nikdy zavolán.
-For example:
-- When the program fully terminates its operation (for example, when closing a tab in a browser).
-- When the `FinalizationRegistry` instance itself is no longer reachable to JavaScript code.
- If the object that creates the `FinalizationRegistry` instance goes out of scope or is deleted, the cleanup callbacks registered in that registry might also not be invoked.
+Například:
+- Když běh programu zcela skončí (např. při zavření záložky v prohlížeči).
+- Když se samotná instance `FinalizationRegistry` stane nedosažitelnou z JavaScriptového kódu.
+ Jestliže objekt, který vytvořil instanci třídy `FinalizationRegistry`, opustí rozsah platnosti nebo bude smazán, úklidové callbacky registrované v tomto registru nemusejí být vyvolány.
-## Caching with FinalizationRegistry
+## Ukládání do mezipaměti pomocí FinalizationRegistry
-Returning to our *weak* cache example, we can notice the following:
-- Even though the values wrapped in the `WeakRef` have been collected by the garbage collector, there is still an issue of "memory leakage" in the form of the remaining keys, whose values have been collected by the garbage collector.
+Když se vrátíme k našemu příkladu *slabé* mezipaměti, můžeme si všimnout následujícího:
+- I když byly hodnoty zabalené do `WeakRef` odklizeny sběračem odpadků, stále je tady problém s „únikem paměti“ v podobě zbývajících klíčů, jejichž hodnoty sběrač odpadků odstranil.
-Here is an improved caching example using `FinalizationRegistry`:
+Následuje vylepšený příklad mezipaměti s využitím `FinalizationRegistry`:
```js
-function fetchImg() {
- // abstract function for downloading images...
+function stáhniObrázek() {
+ // abstraktní funkce pro načítání obrázků...
}
-function weakRefCache(fetchImg) {
- const imgCache = new Map();
+function najdiVMezipaměti(stáhniObrázek) {
+ const paměťObrázků = new Map();
*!*
- const registry = new FinalizationRegistry((imgName) => { // (1)
- const cachedImg = imgCache.get(imgName);
- if (cachedImg && !cachedImg.deref()) imgCache.delete(imgName);
+ const registr = new FinalizationRegistry((názevObrázku) => { // (1)
+ const obrázekVPaměti = paměťObrázků.get(názevObrázku);
+ if (obrázekVPaměti && !obrázekVPaměti.deref()) paměťObrázků.delete(názevObrázku);
});
*/!*
- return (imgName) => {
- const cachedImg = imgCache.get(imgName);
+ return (názevObrázku) => {
+ const obrázekVPaměti = paměťObrázků.get(názevObrázku);
- if (cachedImg?.deref()) {
- return cachedImg?.deref();
+ if (obrázekVPaměti?.deref()) {
+ return obrázekVPaměti?.deref();
}
- const newImg = fetchImg(imgName);
- imgCache.set(imgName, new WeakRef(newImg));
+ const novýObrázek = stáhniObrázek(názevObrázku);
+ paměťObrázků.set(názevObrázku, new WeakRef(novýObrázek));
*!*
- registry.register(newImg, imgName); // (2)
+ registr.register(novýObrázek, názevObrázku); // (2)
*/!*
- return newImg;
+ return novýObrázek;
};
}
-const getCachedImg = weakRefCache(fetchImg);
+const vraťObrázekVPaměti = najdiVMezipaměti(stáhniObrázek);
```
-1. To manage the cleanup of "dead" cache entries, when the associated `WeakRef` objects are collected by the garbage collector, we create a `FinalizationRegistry` cleanup registry.
+1. Abychom zajistili úklid „mrtvých“ záznamů v mezipaměti, když jsou připojené objekty ve `WeakRef` odklizeny sběračem odpadků, vytvoříme úklidový registr `FinalizationRegistry`.
- The important point here is, that in the cleanup callback, it should be checked, if the entry was deleted by the garbage collector and not re-added, in order not to delete a "live" entry.
-2. Once the new value (image) is downloaded and put into the cache, we register it in the finalizer registry to track the `WeakRef` object.
+ Důležitým bodem zde je, že v úklidovém callbacku bychom měli ověřovat, zda záznam byl odstraněn sběračem odpadků a nebyl znovu přidán, abychom nesmazali „živý“ záznam.
+2. Když je stažena a umístěna do mezipaměti nová hodnota (obrázek), zaregistrujeme ji v registru finalizátorů, abychom mohli sledovat objekt `WeakRef`.
-This implementation contains only actual or "live" key/value pairs.
-In this case, each `WeakRef` object is registered in the `FinalizationRegistry`.
-And after the objects are cleaned up by the garbage collector, the cleanup callback will delete all `undefined` values.
+Tato implementace obsahuje pouze aktuální neboli „živé“ dvojice klíč/hodnota. V tomto případě je každý objekt `WeakRef` zaregistrován ve `FinalizationRegistry` a poté, co jsou objekty odstraněny sběračem odpadků, úklidový callback smaže všechny hodnoty `undefined`.
-Here is a visual representation of the updated code:
+Na obrázku je vizuální reprezentace vylepšeného kódu:

-A key aspect of the updated implementation is that finalizers allow parallel processes to be created between the "main" program and cleanup callbacks.
-In the context of JavaScript, the "main" program - is our JavaScript-code, that runs and executes in our application or web page.
+Klíčovým aspektem vylepšené implementace je, že finalizátory umožňují vytváření paralelních procesů mezi „hlavním“ programem a úklidovými callbacky. V kontextu JavaScriptu je „hlavním“ programem náš JavaScriptový kód, který je spuštěn a běží v naší aplikaci nebo webové stránce.
-Hence, from the moment an object is marked for deletion by the garbage collector, and to the actual execution of the cleanup callback, there may be a certain time gap.
-It is important to understand that during this time gap, the main program can make any changes to the object or even bring it back to memory.
+Proto může mezi okamžikem, kdy je objekt označen ke smazání sběračem odpadků, a skutečným spuštěním úklidového callbacku nastat určitá časová prodleva. Je důležité pochopit, že během této prodlevy může hlavní program provést v objektu jakékoli změny nebo jej dokonce vrátit zpět do paměti.
-That's why, in the cleanup callback, we must check to see if an entry has been added back to the cache by the main program to avoid deleting "live" entries.
-Similarly, when searching for a key in the cache, there is a chance that the value has been deleted by the garbage collector, but the cleanup callback has not been executed yet.
+Z tohoto důvodu musíme v úklidovém callbacku ověřovat, zda hlavní program nepřidal záznam zpět do mezipaměti, abychom se vyhnuli mazání „živých“ záznamů. Obdobně když v mezipaměti hledáme klíč, je možné, že jeho hodnota byla vymazána sběračem odpadků, ale úklidový callback ještě nebyl spuštěn.
-Such situations require special attention if you are working with `FinalizationRegistry`.
+Takové situace vyžadují při práci s `FinalizationRegistry` zvláštní pozornost.
-## Using WeakRef and FinalizationRegistry in practice
+## Použití WeakRef a FinalizationRegistry v praxi
-Moving from theory to practice, imagine a real-life scenario, where a user synchronizes their photos on a mobile device with some cloud service
-(such as [iCloud](https://en.wikipedia.org/wiki/ICloud) or [Google Photos](https://en.wikipedia.org/wiki/Google_Photos)),
-and wants to view them from other devices. In addition to the basic functionality of viewing photos, such services offer a lot of additional features, for example:
+Přejděme od teorie k praxi. Představte si scénář ze skutečného života, kdy si uživatel synchronizuje své fotografie na mobilním zařízení s nějakou cloudovou službou (např. [iCloud](https://cs.wikipedia.org/wiki/ICloud) nebo [Fotky Google](https://cs.wikipedia.org/wiki/Fotky_Google)) a chce si je prohlížet z jiných zařízení. Takové služby nabízejí kromě základní functionality prohlížení fotografií řadu dalších funkcí, například:
-- Photo editing and video effects.
-- Creating "memories" and albums.
-- Video montage from a series of photos.
-- ...and much more.
+- Editaci fotografií a videoefektů.
+- Vytváření „vzpomínek“ a alb.
+- Montáž videa ze série fotografií.
+- ...a mnoho dalšího.
-Here, as an example, we will use a fairly primitive implementation of such a service.
-The main point - is to show a possible scenario of using `WeakRef` and `FinalizationRegistry` together in real life.
+Jako příklad zde uvedeme poměrně primitivní implementaci takové služby. Hlavním smyslem je ukázat možný scénář společného použití `WeakRef` a `FinalizationRegistry` ve skutečném životě.
-Here is what it looks like:
+Bude to vypadat následovně:

weakRefCache function checks whether the required image is in the cache.
-If not, it downloads it from the cloud and puts it in the cache for further use.
-This happens for each selected image:
+Předpokládejme, že potřebujeme vytvořit koláž čtyř fotografií: vybereme si je a pak klikneme na tlačítko „Vytvořit koláž“. V tuto chvíli funkce najdiVMezipaměti, kterou už známe, ověří, zda je požadovaný obrázek v mezipaměti. Pokud ne, stáhne jej z cloudu a uloží jej do mezipaměti pro další použití. To se bude odehrávat pro každý zvolený obrázek:
Messages:
- +Zprávy:
+Hello -
Ahoj +
| 1 |
| 1 |
| ` z ` |