-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngSocket.js
55 lines (47 loc) · 1.37 KB
/
ngSocket.js
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
angular.module('ngSocket', []).factory('$socket', ['$rootScope', function ($rootScope) {
if (typeof socket === 'undefined') {
var socket = io.connect();
}
var angularCallback = function (callback) {
return function () {
if (callback) {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
}
};
};
var addListener = function (name, scope, callback) {
if (arguments.length === 2) {
scope = null;
callback = (typeof arguments[1] == "undefined") ? arguments[1] : null;
}
socket.addListener(name, angularCallback(callback));
if (scope !== null) {
scope.$on('$destroy', function () {
removeListener(name, callback);
});
}
};
var addListenerOnce = function (name, callback) {
socket.once(name, angularCallback(callback));
};
var removeListener = function (name, callback) {
socket.removeListener(name, angularCallback(callback));
};
var removeAllListeners = function (name) {
socket.removeAllListeners(name);
};
var emit = function (name, data, callback) {
socket.emit(name, data, angularCallback(callback));
};
return {
addListener: addListener,
on: addListener,
once: addListenerOnce,
removeListener: removeListener,
removeAllListeners: removeAllListeners,
emit: emit
};
}]);