Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR JavaScript client universal trigger

I need to attach an event to every hub.client method. For example:

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

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

Is there a way to attach aFunction() to all client methods on the client level, without placing the function in each client method?

like image 825
LastTribunal Avatar asked Jul 19 '26 06:07

LastTribunal


2 Answers

I don't know about such callback available directly on hub proxy, but you could use received callback on connection object. (see list of connection lifetime events and received definition)

Be aware that received callback is called every time data is received by connection, this means, that if you have multiple hubs, it will be invoked when any of hub send data to client. This means, that you will have to inspect data received in callback and decide, if you should process this data (if it belongs to given hub, if it is real message, or just signalr internal message).

like image 183
Marian Polacek Avatar answered Jul 20 '26 19:07

Marian Polacek


With some JavaScript code you can achieve what you need, regardless of 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 extend function on all your hub proxies after having defined your real handlers.

With some more effort this code can be made more solid and generic, but I think it should already put you in the right direction.

like image 30
Wasp Avatar answered Jul 20 '26 20:07

Wasp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!