This repository has been archived by the owner on Oct 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 102
/
fanout.js
56 lines (53 loc) · 1.97 KB
/
fanout.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
window.Fanout = (function() {
var _loaded = false;
var _client = null;
var _locks = {};
var config = $('fanout-config');
var loadJS = function loadJS(cb) {
if (_loaded) {
return cb();
}
var script = document.createElement('script');
script.crossOrigin = 'anonymous';
script.integrity = config.data('js-sha');
script.onload = function() {
loaded = true;
cb();
};
script.src = config.data('js-url');
document.head.appendChild(script);
};
return {
/* This function wraps fanout's client. The purpose is to have throttle
the callbacks. It's not unrealistic that the server side will fire
events repeatedly. Because often the events are fired by ORM signals.
*/
subscribe: function(channel, cb) {
loadJS(function() {
if (_client === null) {
_client = new Faye.Client(config.data('client-url'), {
// What this means is that we're opting to have
// Fanout *start* with fancy-pants WebSocket and
// if that doesn't work it **falls back** on other
// options, such as long-polling.
// The default behaviour is that it starts with
// long-polling and tries to "upgrade" itself
// to WebSocket.
transportMode: 'fallback'
});
}
_client.subscribe(channel, function(data) {
if (_locks[channel]) {
// throttled
return;
}
_locks[channel] = true;
cb(data);
setTimeout(function() {
_locks[channel] = false;
}, 500);
});
});
}
};
})();