I'm building a simple chatApp. The UI has just 3 interaction areas: input, submit and previous messages button.
But I'm not interested in reviewing the app architecture as much as the javascript ideas and general understanding/errors.
I've commented the code, and would like to see if you can point out any bad practice. I'm sure most of the code is bad, but still, the most important errors.
I've also included the UI as a runnable snippet.
Any edits to make it better for reviewers will be done.
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#wantMore{
position:absolute;
top:0;
right:0;
}
</style>
</head>
<body>
<button id="wantMore">More</button>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="mySnippet"></script>
<script src="socket-io.js"></script>
</body>
</html>
const prevMsgs = document.querySelector("button#wantMore")
const uri = "http://localhost:3000"
class Msg {
constructor (msg, createdAt){
this.msg = msg
this.createdAt = createdAt
}
static toHTML ({msg, createdAt}) {
// pass object, builds list item.
try{
//in case the date conversion fails.
createdAt = (new Date(createdAt))
.toTimeString()
.substr(0,5)
} catch(e){ console.log(e) }
finally{ createdAt || "" }
return `<li><span>${msg}</span> <span>${createdAt}</span></li>`
}
static put (data) {
$("#messages").prepend(this.toHTML(data))
}
static getMsgs (uri, skip, limit) {
//returns a promise, errors are catch
return fetch(`${uri}/messages/skip/${skip}/limit/${limit}`)
.then(data => data.json())
.then(items => items.forEach(item => this.put(item)))
}
static getLastMsgs (uri) { return this.getMsgs(uri, 0,10) }
}
$(function () { // $(document).ready(
Msg.getLastMsgs(uri).catch(e => console.log(e))
prevMsgs.addEventListener("click", () => {
const msgLen = parseInt($("#messages").children().length)
Msg.getMsgs(uri, msgLen, msgLen+10)
})
const socket = io(); //connects to / origin
$('form').submit(function(e) {
e.preventDefault(); // prevents page reloading
const msg = new Msg($('#m').val(), new Date())
//for the sender, append right away.
$("#messages").append(Msg.toHTML(msg))
// and emit, and broadcast
socket.emit('chat message', msg);
$('#m').val('');
return false;
});
socket.on('chat message', data => {
$("#messages").append(Msg.toHTML(data))
})
})
```