I have a notifications button on my page which indicates the number of notifications that are currently pending for a user.
I thought that I would be right to use SignalR for this, as I wish to open a connection, periodically check for an update to this notification count and then update the DOM.
I expected that I could do the following using SignalR, but I don't know how to periodically check for changes.
I thought that I had it right with the following code:
SignalR Hub
[Authorize]
public class NotificationHub : Hub
{
private IQuizEntities DbContext;
public NotificationHub(IQuizEntities dbContext)
{
this.DbContext = dbContext;
}
public void GetNotificationCount()
{
int userId = Context.User.Identity.GetUserId<int>();
// Get the notification count for the logged in user
int notificationCount = (from notification in this.DbContext.EntitySet<Notification>()
where notification.UserId == userId
select notification).Count();
// If there are any notificatoins, inform the client
if (notificationCount > 0)
{
Clients.Caller.updateNotificationCount(notificationCount);
}
}
}
Javascript:
function NotificationHeartbeat() {
var notificationHubProxy = $.connection.notificationHub;
notificationHubProxy.client.updateNotificationCount = function (notificationCount) {
$('span#notification_count').html(notificationCount);
// Change colour of button
if (notificationCount < 1) {
$('#notification_button').removeClass('notification_button_active');
} else {
$('#notification_button').addClass('notification_button_active');
}
};
// Start the connection
$.connection.hub.start().done(function () {
// Do something
});
}
But sadly it never updates the DOM... I thought that SignalR could be used to long-poll the server periodically?
I notice that the difference between my use case and the other one's that I've seen, is that SignalR sends out signals when a request comes along from another user doing something. I don't want to do that, I just want my server to periodically check for the number of notifications, just like any other rest service. Maybe I should just be using long polling in ajax.