-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (54 loc) · 1.27 KB
/
index.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
/**
* Module dependencies
*/
var ws = require('engine.io');
var angular = window.angular;
/**
* Create the hyper-emitter-ws module
*/
var pkg = module.exports = angular.module('ng-hyper-emitter-ws', ['ng-hyper']);
/**
* Factory for connecting to a emitter endpoint
*/
pkg.factory('hyperEmitterWs', [
'hyperHttpEmitter',
function(emitter) {
var count = 0;
var socks = {};
var urls = {};
function sendAll(url, add) {
angular.forEach(socks, function(sock) {
send(sock, url, add);
});
}
function send(sock, url, add) {
sock.send((add ? '+' : '-') + url);
}
emitter.subscribe(function(url) {
urls[url] = true;
sendAll(url, true);
});
emitter.unsubscribe(function(url) {
delete urls[url];
sendAll(url, false);
});
return function(uri, opts) {
var id = count++;
var sock = ws(uri, opts);
sock.on('close', function() {
delete socks[id];
sock.open();
});
sock.on('open', function() {
socks[id] = sock;
angular.forEach(urls, function(_, url) {
send(sock, url, true);
});
});
sock.on('message', function(url) {
emitter.refresh(url);
});
};
}
]);
pkg.name = 'ng-hyper-emitter-ws';