-
Notifications
You must be signed in to change notification settings - Fork 924
/1-js/06-data-storage/02-localstorage #123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Первые предложения для улучшения перевода.
Please make the requested changes. After it, add a comment "/done". |
/done |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ещё изменения + не все правки внесены с предыдущего ревью.
Please make the requested changes. After it, add a comment "/done". |
/done |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пожалуйста, внеси изменения. По большей части улучшения изложения. Спасибо!
# LocalStorage, sessionStorage | ||
|
||
Web storage objects `localStorage` and `sessionStorage` allow to save key/value pairs in the browser. | ||
объекты веб-хранилища `localStorage` и `sessionStorage` позволяют хранить пары ключ/значение в браузере. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Объекты
объекты веб-хранилища `localStorage` и `sessionStorage` позволяют хранить пары ключ/значение в браузере. | ||
|
||
What's interesting about them is that the data survives a page refresh (for `sessionStorage`) and even a full browser restart (for `localStorage`). We'll see that very soon. | ||
И что самое интересное: данные сохраняются после обновления страницы (в случае `sessionStorage`) и даже при перезагрузки браузера (при использовании `localStorage`). Скоро мы это увидим. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Что в них важно - данные, которые в них записаны, сохраняются после обновления страницы (в случае sessionStorage
) и даже после перезагрузки браузера (при использовании localStorage
). Скоро мы это увидим.
И что самое интересное: данные сохраняются после обновления страницы (в случае `sessionStorage`) и даже при перезагрузки браузера (при использовании `localStorage`). Скоро мы это увидим. | ||
|
||
We already have cookies. Why additional objects? | ||
Но у нас также есть куки. Зачем тогда эти объекты? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Но ведь у нас уже есть куки.
- Unlike cookies, web storage objects are not sent to server with each request. Because of that, we can store much more. Most browsers allow at least 2 megabytes of data (or more) and have settings to configure that. | ||
- The server can't manipulate storage objects via HTTP headers, everything's done in JavaScript. | ||
- The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can't access data from each other. | ||
- В отличие от кук, объекты веб-хранилища не отправляются на сервер при каждом запросе. Поэтому мы можем хранить гораздо больше данных. Большинство браузеров могут сохранить как минимум 2 мегабайта данных (или больше), и этот размер можно изменить. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
, и этот размер можно поменять в настройках.
- The server can't manipulate storage objects via HTTP headers, everything's done in JavaScript. | ||
- The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can't access data from each other. | ||
- В отличие от кук, объекты веб-хранилища не отправляются на сервер при каждом запросе. Поэтому мы можем хранить гораздо больше данных. Большинство браузеров могут сохранить как минимум 2 мегабайта данных (или больше), и этот размер можно изменить. | ||
- Сервер не может манипулировать объектами хранилища через HTTP-заголовки, все делается при помощи JavaScript. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ещё одно отличие от куки - сервер не может манипулировать объектами хранилища через HTTP-заголовки. Все делается при помощи JavaScript.
- `getItem(key)` -- получить данные используя ключ (key). | ||
- `removeItem(key)` -- удалить пару ключ/значение используя ключ (key). | ||
- `clear()` -- удалить всё. | ||
- `key(index)` -- получить ключ заданной позиции (index). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
на заданной позиции
- Triggers on all `window` objects that have access to the storage except the one that generated it (within a tab for `sessionStorage`, globally for `localStorage`). | ||
- Срабатывает при вызове `setItem`, `removeItem`, `clear`. | ||
- Содержит все данные об операции, `url` документа и объект хранилища. | ||
- Срабатывает на всех `window` объектах которые имеют доступ к хранилищу, а также там, где оно было сгенерировано (на вкладке для `sessionStorage`, глобально для `localStorage`). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Срабатывает на всех объектах window
, которые
- `key(index)` -- get the key on a given position. | ||
- `length` -- the number of stored items. | ||
- `setItem(key, value)` -- сохранить пару ключ/значение (key/value). | ||
- `getItem(key)` -- получить данные используя ключ (key). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
получить данные по ключу key
- `length` -- the number of stored items. | ||
- `setItem(key, value)` -- сохранить пару ключ/значение (key/value). | ||
- `getItem(key)` -- получить данные используя ключ (key). | ||
- `removeItem(key)` -- удалить пару ключ/значение используя ключ (key). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
удалить данные с ключом key
Please make the requested changes. After it, add a comment "/done". |
``` | ||
|
||
We only have to be on the same domain/port/protocol, the url path can be different. | ||
Нам достаточно находится на том же домен/протокол/порт, но при этом путь url может быть разным. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
находитЬся
Это возможно по историческим причинам и как правило работает, но обычно не рекомендуется по двум причинам: | ||
|
||
1. If the key is user-generated, it can be anything, like `length` or `toString`, or another built-in method of `localStorage`. In that case `getItem/setItem` work fine, while object-like access fails: | ||
1. Если ключ генерируется пользователем, то он может быть каким угодно, включая `length` или `toString`, а также другой встроенный метод `localStorage`. В этом случае `getItem/setItem` работает нормально, до тех пор, пока объектно-ориентированный доступ потерпит неудачу: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@iliakan может "чтение/запись свойства объекта не пРойдут? а то не могу понять фразу
Обратите внимание, что событие также содержит: `event.url` - url-адрес документа, в котором данные обновились. | ||
|
||
Also, `event.storageArea` contains the storage object -- the event is the same for both `sessionStorage` and `localStorage`, so `storageArea` references the one that was modified. We may event want to set something back in it, to "respond" to a change. | ||
Также `event.storageArea` содержит объект хранилища - событие одинаковое для `sessionStorage` и `localStorage`, поэтому `storageArea` ссылается на тот который был изменен. Мы можем захотеть что-то вернуть обратно, "ответить" на изменения. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тот, который
**Это позволяет разным окнам одного источника обмениваться сообщениями.** | ||
|
||
Modern browsers also support [Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API), the special API for same-origin inter-window communication, it's more full featured, but less supported. There are libraries that polyfill that API, based on `localStorage`, that make it available everywhere. | ||
Современные браузеры также поддерживают [Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API) специальный API для связи между окнами одного источника, он более полнофункциональный, но менее поддерживаемый. Существуют библиотеки (полифилы), которые дополняют API на основе `localStorage`, и делают его доступным везде. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
перед делают не надо , вроде
- Use `Object.keys` to get all keys. | ||
- Can use the keys as object properties, in that case `storage` event doesn't trigger. | ||
- `setItem(key, value)` -- сохранить пару ключ/значение (key/value). | ||
- `getItem(key)` -- получить данные используя ключ (key). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
, используя
- Can use the keys as object properties, in that case `storage` event doesn't trigger. | ||
- `setItem(key, value)` -- сохранить пару ключ/значение (key/value). | ||
- `getItem(key)` -- получить данные используя ключ (key). | ||
- `removeItem(key)` -- удалить пару ключ/значение используя ключ (key). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
, используя
Please make the requested changes. After it, add a comment "/done". |
Please make the requested changes. After it, add a comment "/done". |
как вариант, можно обновить форк и сделать новый PR, скопировав туда перевод главы. |
А вот это мне нравиться больше) в какой то момент все пошло не так. И вместо перевода борюсь с гитом |
Ждём =) |
/done |
В Files changed по-прежнему много файлов |
И еще правки не учтены. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Правки не учтены, файлы лишние.
Please make the requested changes. After it, add a comment "/done". |
Как можно от этих файлов избавиться? Склонировал форк в новую папку. Затем сделал git pull с основного репозитория в мастер. git pull upstream master. Далее git merge master. Затем сделал коммит только одного файла и запушил. Новый pull request мне поможет? |
Реально ты менял только текст одного файла, да? |
Я там видел - мои правки по тексту не все учтены, как минимум одна =) |
меняю только один файл и добавляю его в коммит. Не могу понять каким образом добавились еще 45 файлов. |
Пересмотрю) |
Прими все правки по этому файлу и создай абсолютно новый PR только с ним. Можешь репу с нуля переклонировать или как проще =) |
Сейчас вот такая картина (если сделаю PR должно быть ок?):
Changes not staged for commit:
|
Там теперь 61 файл, а было 45)) Может просто создать новый форк и новый PR и скопировать только статью с переводом? |
да |
Сделал новый форк и PR (#301 ) |
В связи с перепетиями с гитом этот PR зашел в тупик, продолжение в #301 |
Перевод страницы 6-data-storage/02-localstorage/article.md
localStorage и sessionStorage