Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 737
viking Avatar asked Sep 11 '15 14:09

viking


2 Answers

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.

like image 117
Alex Avatar answered Sep 24 '22 14:09

Alex


it is an old question but as I found the solution in my case so updating it may help someone. So in my case, as apiMsgProxy is a global variable so each time page refreshes and reloaded it will register the SendSaleUpdate function each time and as many times as it registered it will be called that many time

like image 42
Chitta Avatar answered Sep 24 '22 14:09

Chitta