Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.factory('signalr', ['$rootScope', '$timeout', function ($rootScope, $timeout) {
function signalrProxyFactory(hubName, startedCallback, startOptions) {
var connection = $.hubConnection();
var proxy = connection.createHubProxy(hubName);
// required by SignalR to work... we need to attach at least one handler
// to the proxy before calling 'start'
proxy.on('stub', function () { });
var startPromise = connection.start(startOptions);
if (startedCallback) {
startPromise.done(function() {
var currentPhase = $rootScope.$$phase;
//console.log('phase : ' + currentPhase, 'conn id: ' + connection.id);
function applyCallback() {
$rootScope.$apply(function () {
startedCallback();
});
}
if (!currentPhase) {
applyCallback();
} else {
$timeout(applyCallback);
}
});
}
return {
connection: connection,
on: function(eventName, callback) {
var attachedCallback = function(result) {
$rootScope.$apply(function() {
if (callback) {
callback(result);
}
});
};
proxy.on(eventName, attachedCallback);
return attachedCallback;
},
off: function(eventName, callback) {
proxy.off(eventName, callback);
},
invoke: function(methodName, param, callback) {
proxy.invoke(methodName, param).done(function(result) {
$rootScope.$apply(function() {
if (callback) {
callback(result);
}
});
});
}
};
};
return signalrProxyFactory;
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.