-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignalR.module.js
More file actions
109 lines (96 loc) · 3.25 KB
/
Copy pathsignalR.module.js
File metadata and controls
109 lines (96 loc) · 3.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* AngularJs module simplifying the work with SignalR hub proxies. No need to explicitly start the connection to a hub.
* Requires angular.js
* @example: hubFactory.getHub("myHub").run("myMethod", param_1, param_2, .... param_n).then ( function(responseData) {} )
*/
angular.module("dataAccess.SignalRModule", []).factory("hubFactory", ["$q", "$rootScope", function ($q, $rootScope) {
"use strict";
// log signalR client-side messages
$.connection.hub.logging = true;
/**
* Hub constructor.
*
* @class Hub
* @constructor
* @param {String} SignalR hub name
*/
function Hub(strHubName) {
if (!strHubName) {
throw new Error("Hub name not defined!");
}
this.hub = $.connection[strHubName];
if (this.hub === undefined) {
throw new Error("Hub with name " + strHubName + " doesn't exist.");
}
}
/**
* Runs a method on the SignalR hub proxy asynchronously.
*
* @method run
* @param {String} proxy method name
* @return {Promise} Returns promise
*/
Hub.prototype.run = function (methodName) {
var self = this;
var args = arguments;
var def = $q.defer();
if (!$.connection.hub) {
window.setTimeout(
function () {
_safeApply(def.reject, "Hub not available.");
}, 0);
return def.promise;
}
function _init() {
return $.connection.hub.start();
};
// calls apply on the root scope
function _safeApply(methodRef, arg) {
if (!$rootScope.$$phase) {
$rootScope.$apply(function () {
methodRef.call(def, arg);
});
}
else {
methodRef.call(def, arg);
}
}
// calls the hub method and resolves the promise
function _resolveMethodCall() {
try {
var response = self.hub.invoke.apply(self.hub, args);
_safeApply(def.resolve, response);
}
catch (err) {
_safeApply(def.reject, response);
}
}
switch ($.connection.hub.state) {
case $.signalR.connectionState.connected:
_resolveMethodCall();
break;
case $.signalR.connectionState.disconnected:
_init().done(function () {
_resolveMethodCall();
}).fail(function (err) {
_safeApply(def.reject, err);
});
break;
case $.signalR.connectionState.connecting:
case $.signalR.connectionState.reconnecting:
default:
$.connection.hub.stateChanged(function (state) {
if (state.newState === $.signalR.connectionState.connected)
_resolveMethodCall();
});
break;
}
return def.promise;
}
// returns an Object containing a method that returns a required SignalR hub
return {
getHub: function (hubName) {
return new Hub(hubName);
}
};
}]);