Search code examples
jqueryangularjssignalrasp.net-web-api2signalr.client

SignalR client callback method getting called multiple times


We have a SignalR client call back method, which gets called as many times as we move away from and come back to it's containing page. For example: page is salesUpdate.html (Angular template), on this page when coming for the first time, the call back would execute once upon it's event. Now when we move away from this page to another page (say purchaseUpdate.html), and come back to this page i.e. salesUpdate.html, this SignalR client call back method would execute twice. It will execute as many times as we move away from the page and come back to it. From server, this method is called from ASP.NET Web API, and Web API is hit only one time, all subsequent execution of call back does not hit Web API. Here is the client call back method:

var con;
var apiMsgProxy;
$(document).ready(function () {
        con = $.hubConnection('http://localhost:51123/signalr');
        apiMsgProxy = con.createHubProxy('salesHub');

        apiMsgProxy.on('SendSaleUpdate', function (uMsg) {
            console.log("Call back SendSaleUpdate called - " + uMsg);
        });
        con.start().done(function () {
        console.log("SignalR connection opened - " + con.state);
        }).fail(function () { 
            console.log('Could not Connect SignalR hub!'); 
        });
});

Any pointer towards this will be greatly appreciated.


Solution

  • I know that this question was asked a long time ago. But I had the same issue and found a solution. Thought I'd share it with everyone. In the question, the "salesHub" gets inited and event handler is being added using the hub's .on("SendSaleUpdate") method on page load. Apparently, if you don't "turn off" that handler it'll be invoked by SignalR as mane times as the client inited the hub (visited the same page while the same connection is still opened.) To prevent this from happening, you need to call hub's .off("SendSaleUpdate") method when the user leaves the page. That solved the same issue for me.