Search code examples
javascriptjquerysignalrjquery-callbacksignalr.client

Use jquery callback instead of RPC in SignalR hub


I need to subscribe to the same hub several times from different places, e.g.:

function firstPlace(targetHub){
  targetHub.client.onSomeEvent = function(data){
     alert('hello from first place');
  };
}
function secondPlace(targetHub){
  targetHub.client.onSomeEvent = function(data){
     alert('hello from second place');
  };
}

firstPlace($.connection.clientHub);
secondPlace($.connection.clientHub);

I'd like to have functionality based on callbacks (like jquery callbacks).

function firstPlace(targetHub){
  targetHub.client.onSomeEvent.add(function(data){
     alert('hello from first place');
  });
}
function secondPlace(targetHub){
  targetHub.client.onSomeEvent.add(function(data){
     alert('hello from second place');
  });
}


firstPlace($.connection.clientHub);
secondPlace($.connection.clientHub);

I know it can be easily implemented using some proxy object, but maybe there are some javascript magic that i'm not aware of?


Solution

  • If you don't help yourself, no one else will =). Here is the code, that solve my problem:

    signalR.FunctionToCallback = new function() {
      self.MapCallback = function (sourceFunction, targetCallback) {
          if (!sourceFunction) {
              sourceFunction = function () {
                  sourceFunction.callbacks.fireWith(this, $.makeArray(arguments));
              };
          }
          if (!sourceFunction.callbacks) {
              sourceFunction.callbacks = $.Callbacks();
          }
          sourceFunction.callbacks.add(targetCallback);
          return sourceFunction;
      };
    };
    

    Usage example:

    function firstPlace(targetHub){
      targetHub.client.onSomeEvent = ko.FunctionToCallback.MapCallback(targetHub.client.onSomeEvent,function(data){
         alert('hello from first place');
      });
    }
    function secondPlace(targetHub){
      targetHub.client.onSomeEvent = ko.FunctionToCallback.MapCallback(targetHub.client.onSomeEvent, function(data){
         alert('hello from second place');
      });
    }
    firstPlace($.connection.clientHub);
    secondPlace($.connection.clientHub);