LastTribunal
LastTribunal

Reputation: 1

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?

Upvotes: 3

Views: 194

Answers (2)

Wasp
Wasp

Reputation: 3425

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.

Upvotes: 1

Marian Polacek
Marian Polacek

Reputation: 2925

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).

Upvotes: 1

Related Questions