Lucas
Lucas

Reputation: 376

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.

Upvotes: 2

Views: 1416

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13498

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.");
    //});
}

Upvotes: 3

Related Questions