How do I make a SignalR client something when it receives a message?
- by Ben
I want to do something when a client receives a message via a SignalR hub.
I've put together a basic chat app, but want people to be able to "like" a chat comment. I'm thinking the way to do this is to find the chat message on the client's page and update it using javascript. In the meantime to "prove the concept" I just want to make an alert popup on the client machine to say another user likes the comment.
Trouble is, I'm not sure where to put it. (Am struggling to find SignalR documentation to be honest.) can't get my head round what is calling what here.
My ChatHub class is as follows:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
And my JavaScript is:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
var divContent = $('#discussion').html();
$('#discussion').html('<div class="container">' +
'<div class="content">' +
'<p class="username">' + encodedName + '</p>' +
'<p class="message">' + encodedMsg + '</p>' +
'</div>' +
'<div class="slideout">' +
'<div class="clickme" onclick="slideMenu(this)"></div>' +
'<div class="slidebutton"><img id="imgid" onclick="likeButtonClick(this)" src="Images/like.png" /></div>' +
'<div class="slidebutton"><img onclick="commentButtonClick(this)" src="Images/comment.png" /></div>' +
'<div class="slidebutton" style="margin-right:0px"><img onclick="redcardButtonClick(this)" src="Images/redcard.png" /></div>' +
'</div>' +
'</div>' + divContent);
};
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#lblUser').html(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});