Insight Insight - 3 months ago 15
C# Question

Signalr connection on layout and view

so I have the following code on my layout page:

$(document).ready(function() {
var connection = $.connection.notificationHub;
connection.client.onTicketUpdated = function (model, user, notificationId) {
....
}

$.connection.hub.start().done(function () {
console.log("Successfully connected to CoreHub.");
});


which the action should happen on any page. So the notification can show up in the main bar. However I have another page lets say Index.cshtml that is loaded through the main layout.

$(document).ready(function () {
var connection = $.connection.notificationHub;
connection.client.onNewTicket = function (model, user, notificationId){
....
};
});


Is there a way to not call start again? Wouldn't that create 1 connection for the onTicketUpdated and another whole one for onNewTicket? Can I not use the hub.start() from the layout.cshtml inside the index.cshtml?

This has been bugging me for a while and all my research I haven't found anything that has fixed it. There has to be some way to do this because making 2 different connections for 2 simple functions seems like major over kill.

Answer

You can try to share connection between two pages:

Layout.cshtml:

var connection;
$(document).ready(function() {
    connection = connection || $.connection.notificationHub;
    connection.client.onTicketUpdated = function (model, user, notificationId) {
        ....
    }
    $.connection.hub.start().done(function () {
         console.log("Successfully connected to CoreHub.");
    });
}

Index.cshtml:

$(document).ready(function() {
    connection = connection || $.connection.notificationHub;
    connection.client.onNewTicket = function (model, user, notificationId) {
        ....
    }
    //$.connection.hub.start().done(function () {
    //     console.log("Successfully connected to CoreHub.");
    //});
}
Comments