Last active
September 4, 2016 10:32
-
-
Save hieven/d679875896ccb1db93622f537a230420 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 初始化 socket | |
const socket = io(); | |
// DOM | |
const messageList = document.querySelector('.chat__list'); | |
const input = document.getElementById('newContent'); | |
const submitBtn = document.getElementById('messageCreateBtn'); | |
let uid = null; | |
// 接收 server 端給的 user id | |
socket.on('new uid', data => (uid = data.id)); | |
function createContentDOM(content) { | |
const dom = document.createElement('div'); | |
dom.className = 'chat__content'; | |
dom.textContent = content; | |
return dom; | |
} | |
function createAuthorDOM(id) { | |
const dom = document.createElement('div'); | |
dom.className = 'chat__author'; | |
dom.textContent = `${id} said:`; | |
return dom; | |
} | |
function createChatDOM(id, content) { | |
const dom = document.createElement('div'); | |
dom.className = 'chat'; | |
dom.appendChild(createAuthorDOM(id)); | |
dom.appendChild(createContentDOM(content)); | |
return dom; | |
} | |
function updateChatList(id, content) { | |
const chat = createChatDOM(id, content); | |
messageList.appendChild(chat); | |
} | |
// 當發訊息的按鈕被點擊時,做 socket 通知 | |
submitBtn.addEventListener('click', e => { | |
e.preventDefault(); | |
const content = input.value; | |
// handel 自己畫面上的更新 | |
updateChatList(uid, content); | |
// 通知 server 端,這個 client 講了一句話 | |
socket.emit('new message', { content }); | |
}); | |
// 其他人會收到這個事件,並更新聊天畫面 | |
socket.on('new message', data => updateChatList(data.id, data.content)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment