Permalink
Fetching contributors…
Cannot retrieve contributors at this time
79 lines (68 sloc) 1.96 KB
{{set . "title" "Chat room"}}
{{template "header.html" .}}
<h1>WebSocket — You are now chatting as {{.user}}
<a href="/">Leave the chat room</a></h1>
<div id="thread">
<script type="text/html" id="message_tmpl">
{{raw "<%"}} if(event.Type == 'message') { %>
<div class="message <%= event.User == '{{.user}}' ? 'you' : '' %>">
<h2>{{raw "<%"}}= event.User %></h2>
<p>
{{raw "<%"}}= event.Text %>
</p>
</div>
{{raw "<%"}} } %>
{{raw "<%"}} if(event.Type == 'join') { %>
<div class="message notice">
<h2></h2>
<p>
{{raw "<%"}}= event.User %> joined the room
</p>
</div>
{{raw "<%"}} } %>
{{raw "<%"}} if(event.Type == 'leave') { %>
<div class="message notice">
<h2></h2>
<p>
{{raw "<%"}}= event.User %> left the room
</p>
</div>
{{raw "<%"}} } %>
{{raw "<%"}} if(event.Type == 'quit') { %>
<div class="message important">
<h2></h2>
<p>
You are now disconnected!
</p>
</div>
{{raw "<%"}} } %>
</script>
</div>
<div id="newMessage">
<input type="text" id="message" autocomplete="off" autofocus>
<input type="submit" value="send" id="send">
</div>
<script type="text/javascript">
// Create a socket
var socket = new WebSocket('ws://'+window.location.host+'/websocket/room/socket?user={{.user}}')
// Display a message
var display = function(event) {
$('#thread').append(tmpl('message_tmpl', {event: event}));
$('#thread').scrollTo('max')
}
// Message received on the socket
socket.onmessage = function(event) {
display(JSON.parse(event.data))
}
$('#send').click(function(e) {
var message = $('#message').val()
$('#message').val('')
socket.send(JSON.stringify(message))
});
$('#message').keypress(function(e) {
if(e.charCode == 13 || e.keyCode == 13) {
$('#send').click()
e.preventDefault()
}
})
</script>