简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM