Skip to content

Instantly share code, notes, and snippets.

@Szil
Created October 31, 2014 14:18
Show Gist options
  • Save Szil/ecd5eb6ded3e1fcb4e56 to your computer and use it in GitHub Desktop.
Save Szil/ecd5eb6ded3e1fcb4e56 to your computer and use it in GitHub Desktop.
chathub
$(function () {
var name = '';
var connected = false;
var numUsers = 0;
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// User Connected to the chat.
chat.client.userConnected = function (name, _) {
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ ' is connected to the chat.</strong>' + '</li>');
$('#numusers').html(_);
}
// Get the user name and store it to prepend to messages.
name = promtUserName();
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
if (name) {
// Call the Send method on the hub.
chat.server.send(name, $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
} else name = promtUserName();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
var tries = 0;
function promtUserName() {
switch (tries) {
case 0:
return prompt('Enter your name:', '');
break;
case 1:
return prompt('Please enter your name to chat:', '');
break;
case 2:
return prompt('Enter your god damn name!', '');
break;
default:
return prompt("Can't chat without a name dude!", "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment