This repository was archived by the owner on Mar 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
83 lines (69 loc) · 2.11 KB
/
Copy pathsocket.js
File metadata and controls
83 lines (69 loc) · 2.11 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
/*
* angular-socket-io v0.2.0
* (c) 2013 Brian Ford http://briantford.com
* License: MIT
*/
'use strict';
angular.module('btford.socket-io', []).
provider('socket', function () {
// when forwarding events, prefix the event name
var prefix = 'socket:',
ioSocket;
// expose to provider
this.$get = function ($rootScope, $timeout) {
var socket = ioSocket || io.connect();
var asyncAngularify = function (callback) {
return function () {
var args = arguments;
$timeout(function () {
callback.apply(socket, args);
}, 0);
};
};
var addListener = function (eventName, callback) {
socket.on(eventName, asyncAngularify(callback));
};
var wrappedSocket = {
on: addListener,
addListener: addListener,
emit: function (eventName, data, callback) {
if (callback) {
socket.emit(eventName, data, asyncAngularify(callback));
} else {
socket.emit(eventName, data);
}
},
removeListener: function () {
var args = arguments;
return socket.removeListener.apply(socket, args);
},
// 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 = $rootScope;
}
events.forEach(function (eventName) {
var prefixed = prefix + eventName;
var forwardEvent = asyncAngularify(function (data) {
scope.$broadcast(prefixed, data);
});
scope.$on('$destroy', function () {
socket.removeListener(eventName, forwardEvent);
});
socket.on(eventName, forwardEvent);
});
}
};
return wrappedSocket;
};
this.prefix = function (newPrefix) {
prefix = newPrefix;
};
this.ioSocket = function (socket) {
ioSocket = socket;
};
});