Permalink
Fetching contributors…
Cannot retrieve contributors at this time
84 lines (73 sloc) 2.07 KB
{{set . "title" "Chat room"}}
{{template "header.html" .}}
<h1>Ajax, long polling — You are now chatting as {{.user}}
<a href="/longpolling/room/leave?user={{.user}}">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 "<%"}} } %>
</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">
var lastReceived = 0
var waitMessages = '/longpolling/room/messages?lastReceived='
var say = '/longpolling/room/messages?user={{.user}}'
$('#send').click(function(e) {
var message = $('#message').val()
$('#message').val('')
$.post(say, {message: message})
});
$('#message').keypress(function(e) {
if(e.charCode == 13 || e.keyCode == 13) {
$('#send').click()
e.preventDefault()
}
})
// Retrieve new messages
var getMessages = function() {
$.ajax({
url: waitMessages + lastReceived,
success: function(events) {
$(events).each(function() {
display(this)
lastReceived = this.Timestamp
})
getMessages()
},
dataType: 'json'
});
}
getMessages();
// Display a message
var display = function(event) {
$('#thread').append(tmpl('message_tmpl', {event: event}));
$('#thread').scrollTo('max')
}
</script>
{{template "footer.html" .}}