-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
79 lines (66 loc) · 1.83 KB
/
Copy pathclient.js
File metadata and controls
79 lines (66 loc) · 1.83 KB
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
'use strict'
const textInput = ( {placeholder} ) => {
const input = document.createElement('input')
input.type = 'text'
input.placeholder = placeholder
return input
}
const button = ( {text} ) => {
const button = document.createElement('button')
button.append(text)
return button
}
const pre = ( {text} ) => {
const pre = document.createElement('pre')
pre.append(text)
return pre
}
const li = ( {item} ) => {
const li = document.createElement('li')
li.append(item)
return li
}
const ul = ( {items} ) => {
const ul = document.createElement('ul')
const children = items.map(item => li({item}))
ul.append(...children)
return ul
}
let nameList = ul({items: []})
const nameInput = textInput({placeholder: 'Your Name'})
const addNameButton = button({text: 'Add Name'})
const app = document.getElementById('app')
app.append(nameInput, addNameButton, nameList)
let updateId = null;
let state = null;
const socket = io({ transports: ['websocket'] })
socket.on('connect', () => {
console.log(`[${socket.id}] Connected.`)
socket.emit('get', (error, data) => {
console.log('get response', error, data)
if (!data.state) {
socket.emit('update', {updateId: data.updateId, newState: {users: []}})
}
})
socket.on('notify', (data) => {
console.log('notify event', data)
updateId = data.updateId
state = data.state
if (state) {
const newNameList = ul( {items: [...state.users]} )
app.replaceChild(newNameList, nameList)
nameList = newNameList
}
})
addNameButton.addEventListener('click', () => {
const newUsers = [...state.users, nameInput.value]
socket.emit(
'update',
{ updateId, newState: { users: newUsers } },
(error, data) => {
console.log('udpate response', error, data)
}
)
nameInput.value = ''
})
})