-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw2.html
80 lines (67 loc) · 2.47 KB
/
hw2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<!DOCTYPE html>
<!-- saved from url=(0043)file:///home/daniyar/MIPT/DataBase/hw2.html -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PouchDB</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css" id="operaUserStyle"></style></head>
<body>
<!-- DOM -->
<div class="App">
<button id="add">Add</button>
<button id="remove">Remove</button>
<button id="sync">Sync</button>
<ul id="list"><li>Уразов</li></ul>
</div>
<!-- Sciprts -->
<script src="./hw2_files/pouchdb.min.js"></script>
<script>
let data = []
const DBS = {
// Создаем локальную БД и коннектимся к удаленной
Local: new PouchDB('docs'),
Remote: new PouchDB('http://admin:1213@localhost:5984/mydatabase')
}
// Иницииируем реприкацию
const sync = DBS.Local.sync(DBS.Remote, {
live: true,
retry: true
}).on('change', ({ change }) => {
// обрабатываем изменения если в процессе синхронизации локлаьной бд таковые произошли
const doc = change.docs[0]
// deleted это просто флаг
if (doc._deleted) {
data = data.filter(item => item._id != doc._id )
} else {
data = data.concat(doc)
}
// рисуем саму html табличку
render(data)
})
const render = data => {
list.innerHTML = data.map(item => `<li>${item.name}</li>`).join('')
}
// получение всех документов
const fetch = () => {
DBS.Local.allDocs({ include_docs: true })
.then(result => {
data = result.rows.map(r => r.doc)
render(data)
})
}
// Events
const addBtn = document.querySelector('#add')
const removeBtn = document.querySelector('#remove')
const list = document.querySelector('#list')
const syncBtn = document.querySelector('#sync')
addBtn.addEventListener('click', () => {
const item = { name: new Date() }
DBS.Local.post(item)
})
removeBtn.addEventListener('click', () => {
const item = data.pop()
if (! item) return
DBS.Local.remove(item)
})
syncBtn.addEventListener('click', () => fetch())
</script>
</body></html>