Skip to content

Instantly share code, notes, and snippets.

@vgheri
Created July 23, 2012 13:40
Show Gist options
  • Save vgheri/3163644 to your computer and use it in GitHub Desktop.
Save vgheri/3163644 to your computer and use it in GitHub Desktop.
$.ready()
$(document).ready(function () {
var chat = new chatR.chatViewModel();
var users = new chatR.connectedUsersViewModel();
var currentUser = new chatR.user(@Html.Raw(Json.Encode(Model))); // The username chose by the user is stored in the model
// Proxy creation
var chatHub = $.connection.chatHub; // chatHub is the name of the Hub as declared in server side code
chatHub.username = currentUser.username; // This is the round-trip state
// Client-side event handlers, as declared inside the Hub
chatHub.onMessageReceived = function (message) {
var date = new Date();
date.setISO8601(message.Timestamp);
chat.messages.push(new chatR.chatMessage(message.Username, message.Content, date));//new Date(message.Timestamp)));
$("#chat-list").scrollTo('max');
}
chatHub.leaves = function (connectionId, username, timestamp) {
var disconnectedUser = new chatR.user(username, connectionId);
users.customRemove(disconnectedUser);
}
chatHub.joins = function (connectionId, username, timestamp) {
var connectedUser = new chatR.user(username, connectionId);
users.contacts.push(connectedUser);
}
function sendMessageContent() {
var content = $("#compose-box").val();
if (content != "" && content != null) {
var msg = new chatR.chatMessage(currentUser.username, content);
chatHub.send(msg).done(function () {
$("#compose-box").val("");
}).fail(function (e) {
alert("Could not connect to server");
});
}
}
$("#send-btn").click(function () {
sendMessageContent();
});
// Handles Enter keystroke press event
$('#compose-box').keypress(function (e) {
if (e.which == 13) {
sendMessageContent();
}
});
ko.applyBindings(users, $("#users-list")[0]);
ko.applyBindings(chat, $("#chat-list")[0]);
// Step 1: Start the connection
// Step 2: Get all currenlty connected users
// Step 3: Join to the chat and nmotify all the clients (me included) that there is a new user connected
$.connection.hub.start()
.done(function () {
chatHub.getConnectedUsers()
.done(function (connectedUsers) {
ko.utils.arrayForEach(connectedUsers, function (item) {
users.contacts.push(new chatR.user(item.Username, item.Id));
});
}).done(function () {
chatHub.joined();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment