Skip to content

Instantly share code, notes, and snippets.

@abariatti
Created February 26, 2015 09:26
Show Gist options
  • Save abariatti/46b2e218a3aaa1359e38 to your computer and use it in GitHub Desktop.
Save abariatti/46b2e218a3aaa1359e38 to your computer and use it in GitHub Desktop.
angularjs factory to ease signalR integration with angularjs. Modified this version http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html to allow to pass any number of parameters to the hub and receive any number of parameters from the hub
'use strict';
angular.module('app')
.value('signalRServer', '')
.factory('signalRHubProxy', ['$rootScope', 'signalRServer', function ($rootScope, signalRServer) {
function signalRHubProxyFactory(serverUrl, hubName, startOptions) {
var connection = $.hubConnection(signalRServer);
var proxy = connection.createHubProxy(hubName);
connection.start(startOptions).done(function () { });
// anonymous function to pass any number of args in $scope.$apply
var clbk = function (args, callback) {
if (callback) callback.apply(this, args);
}
return {
on: function (eventName, callback) {
proxy.on(eventName, function () {
$rootScope.$apply(clbk(arguments, callback));
});
},
off: function (eventName, callback) {
proxy.off(eventName, function () {
$rootScope.$apply(clbk(arguments, callback));
});
},
invoke: function (methodName, args, callback) {
var args = Array.prototype.slice.call(arguments);
if (typeof (arguments[arguments.length - 1]) == "function") {
var callback = args.pop();
}
proxy.invoke.apply(proxy, args)
.done(function (result) {
$rootScope.$apply(clbk(args, callback));
});
},
connection: connection
};
};
return signalRHubProxyFactory;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment