-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
104 lines (80 loc) · 2.81 KB
/
index.js
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const socket = io.connect('http://185.13.90.140:8081/');
class ViewModel {
constructor(socket) {
this.onMessage = this.onMessage.bind(this);
this.socket = socket;
this.nickname = "Guest";
this.messages = [];
this.onChange = () => {};
this.socket.on('message', this.onMessage);
}
onMessage(message) {
if (message.message.startsWith(this.nickname)) {
return;
}
this.messages.push(message);
this.onChange();
}
sendMessage(message) {
socket.emit('message', message);
this.messages.push({
message: message.message
});
this.onChange();
}
}
class View {
constructor(viewModel) {
this.viewModel = viewModel;
this.viewModel.onChange = () => { this.render(); };
this.messagesElement = document.getElementById('messages');
this.nicknameElement = document.getElementById('nickname');
this.messageElement = document.getElementById('message');
this.sendElement = document.getElementById('send');
this.onMessageKeyDown = this.onMessageKeyDown.bind(this);
this.onSendClick = this.onSendClick.bind(this);
this.onNicknameChange = this.onNicknameChange.bind(this);
this.messageElement.onkeydown = this.onMessageKeyDown;
this.sendElement.onclick = this.onSendClick;
this.nicknameElement.onchange = this.onNicknameChange;
}
onMessageKeyDown(args) {
if (args.code === 'Enter') {
this.sendMessage();
}
}
onSendClick() {
this.sendMessage();
}
onNicknameChange() {
this.viewModel.nickname = this.nicknameElement.value;
}
sendMessage() {
this.viewModel.sendMessage({
user: this.nicknameElement.value,
message: this.messageElement.value
});
this.messageElement.value = "";
}
render() {
this.nicknameElement.value = this.viewModel.nickname;
while (this.messagesElement.firstChild) {
this.messagesElement.removeChild(this.messagesElement.firstChild);
}
for (const message of this.viewModel.messages) {
const messageElement = document.createElement('div');
if (message.user) {
messageElement.innerText = `${message.user}: ${message.message}`;
} else {
messageElement.innerText = message.message;
messageElement.className = "current-user-message";
}
this.messagesElement.appendChild(messageElement);
}
this.messagesElement.scrollTo({
behavior: 'smooth',
top: this.messagesElement.scrollHeight,
});
}
}
new View(new ViewModel(socket)).render();