Late binding in SignalR

Once in a while there’s a need to add a callback to signalR after the hubs/connections have been started. Out of the box – you can’t, though its pretty easy to add.

Here’s a solution we’re using for one of internal projects, which basically wraps the hub, and allows to (optionally) add the callbacks at any time:

So, in order to allow a late binding the methods names have to be known, and passed as an array parameter to the constructor.

The call will look something like this:

var userHub = new Hub($.connection.notificationsHub, ['onUserConnected', 'onUserDisconnected', 'notify']);

This will allow to bind methods ‘onUserConnected’‘onUserDisconnected’‘notify’ at a later times:

userHub.Subscribe('onUserConnected',
        function () {
          // code here...
        });


Server can be accessed via a Server property:

userHub.Server.getUsers();

Leave a Reply

Your email address will not be published. Required fields are marked *