Generic trigger for JavaScript SignalR client

I need to bind an event to each hub.client method. For example:

 Hub.client.doSomething = function (e) {
          aFunction(e);
        };

    Hub.client.doSomethingElse = function (e) {
          aFunction(e);
        };

      

Is there a way to bind aFunction()

to all client methods at the client level without putting a function in every client method?

+3


source to share


2 answers


I am not aware of such a callback available directly on the proxy, but you can use a callback received

on the object connection

. (see the list of connection life events and the resulting definition )



Remember that a callback received

is called every time data is received over the connection, which means if you have multiple hubs, it will be called when any of the hubs send data to the client. This means that you have to validate the data received in the callback and decide if you should process that data (if it belongs to the given hub, if it's a real message, or just a signalr message).

+1


source


With some JavaScript, you can achieve what you want, no matter what SignalR provides out of the box:

var extend = function (proxy, ex) {
    var keys = Object.keys(proxy.client),
        aop = function (p, k, f) {
            var prev = p[k];
            return function () {
                f();
                prev.apply(p, arguments);
            };
        };

    keys.forEach(function (k) {
        proxy.client[k] = aop(proxy.client, k, ex);
    });
};

extend(Hub, aFunction);

      



It is enough to call the function extend

on all of your proxies after defining your real handlers.

With even more effort, this code can be made more robust and versatile, but I think it should already put you in the right direction.

+1


source







All Articles