-
Notifications
You must be signed in to change notification settings - Fork 233
/
socket.js
103 lines (87 loc) · 3.18 KB
/
socket.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
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
/*
* @license
* angular-socket-io v0.7.0
* (c) 2014 Brian Ford http://briantford.com
* License: MIT
*/
angular.module('btford.socket-io', []).
provider('socketFactory', function () {
'use strict';
// when forwarding events, prefix the event name
var defaultPrefix = 'socket:',
ioSocket;
// expose to provider
this.$get = ['$rootScope', '$timeout', function ($rootScope, $timeout) {
var asyncAngularify = function (socket, callback) {
return callback ? function () {
var args = arguments;
$timeout(function () {
callback.apply(socket, args);
}, 0);
} : angular.noop;
};
return function socketFactory (options) {
options = options || {};
var socket = options.ioSocket || io.connect();
var prefix = options.prefix === undefined ? defaultPrefix : options.prefix ;
var defaultScope = options.scope || $rootScope;
var addListener = function (eventName, callback) {
socket.on(eventName, callback.__ng = asyncAngularify(socket, callback));
};
var addOnceListener = function (eventName, callback) {
socket.once(eventName, callback.__ng = asyncAngularify(socket, callback));
};
var wrappedSocket = {
on: addListener,
addListener: addListener,
once: addOnceListener,
emit: function (eventName, data, callback) {
var lastIndex = arguments.length - 1;
var callback = arguments[lastIndex];
if(typeof callback == 'function') {
callback = asyncAngularify(socket, callback);
arguments[lastIndex] = callback;
}
return socket.emit.apply(socket, arguments);
},
removeListener: function (ev, fn) {
if (fn && fn.__ng) {
arguments[1] = fn.__ng;
}
return socket.removeListener.apply(socket, arguments);
},
removeAllListeners: function() {
return socket.removeAllListeners.apply(socket, arguments);
},
disconnect: function (close) {
return socket.disconnect(close);
},
connect: function() {
return socket.connect();
},
// when socket.on('someEvent', fn (data) { ... }),
// call scope.$broadcast('someEvent', data)
forward: function (events, scope) {
if (events instanceof Array === false) {
events = [events];
}
if (!scope) {
scope = defaultScope;
}
events.forEach(function (eventName) {
var prefixedEvent = prefix + eventName;
var forwardBroadcast = asyncAngularify(socket, function () {
Array.prototype.unshift.call(arguments, prefixedEvent);
scope.$broadcast.apply(scope, arguments);
});
scope.$on('$destroy', function () {
socket.removeListener(eventName, forwardBroadcast);
});
socket.on(eventName, forwardBroadcast);
});
}
};
return wrappedSocket;
};
}];
});