client.js | |
---|---|
Client side support | |
This file contains all of the relevant client side code to communicate through
| ;(function() {
'use strict' |
Wait for the DOM to load before taking action | $(function() { |
Setup | |
Create the socket connection object, as well as the references to our DOM handlers for input and recording output | var socket = io.connect()
, $messages = $('#messages')
, $input = $('#msg')
, $button = $('#submit')
|
sendSend the input value to the server, recording our own message since | function send() {
socket.emit('message', $input.val())
$messages.prepend('<li><span><b>' + socket.socket.sessionid + '</b></span> ' + $input.val() + '</li>')
$input.val('')
}
|
Socket.io listeners | |
messageA new message has been received, the data comes through as a JSON object with
two attributes, an | socket.on('message', function(data) {
$messages.prepend('<li><span>' + data.id + '</span> ' + data.msg + '</li>')
})
|
connectedAnother client has connected to the application, lets make a note of that, and
add it to the DOM message container with the | socket.on('connected', function(id) {
$messages.prepend('<li class="status"><span>Connected</span> ' + id + '</li>')
}) |
disconnectedAnother client has disconnected from the application | socket.on('disconnected', function(id) {
$messages.prepend('<li class="status"><span>Disconnected</span> ' + id + '</li>')
})
|
User interaction | |
keypress listenerCreate a keystroke listener on the input element, since we are not sending a
traditional form, it would be nice to send the message when we hit | $input.keypress(function(event) {
if (event.which == 13) {
send()
}
})
|
click listenerListen to a | $button.click(send)
})
}).call(this);
|