-
Notifications
You must be signed in to change notification settings - Fork 0
/
horizon-behavior.html
98 lines (73 loc) · 2.93 KB
/
horizon-behavior.html
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
<link rel="import" href="../polymer/polymer.html">
<script>
WIRSENS = window.WIRSENS || {};
var isLoading = false;
/* @polymerBehavior */
WIRSENS.HorizonBehavior = {
properties: {
_horizonHost: String,
_horizonPort: String,
_horizon: {
type: Object,
computed: '_computeHorizon(_horizonHost, _horizonPort, _isReady)',
notify: true
}
},
observers: [
'_loadLib(_horizonHost, _horizonPort)'
],
attached: function () {
this._eventName = 'wirsens-horizon-script-loaded';
var config = new Polymer.IronMetaQuery().byKey('horizon-config');
// it's crucial that we setup our event listeners first, since setting the
// host and port will trigger `_loadLib` which fires an event when the script
// has loaded, so we have to be ready and listening!
this._libLoadedHandler = this._handleLibLoaded.bind(this);
window.addEventListener(this._eventName, this._libLoadedHandler);
this._horizonHost = !!config ? config.host : 'localhost';
this._horizonPort = !!config ? config.port : '8181';
},
_handleLibLoaded: function () {
this._isReady = true;
// we're ready, so let's not listen to events anymore.
window.removeEventListener(this._eventName, this._libLoadedHandler);
},
_loadLib: function (host, port) {
// check if someone else is loading or if we already loaded the script
if (isLoading) {
return;
}
// we're first, let's load it
isLoading = true;
var scriptLoaded = function () {
isLoading = false;
this.fire(this._eventName, {}, { node: window });
}.bind(this);
if (document.querySelector('#horizonScript')) {
scriptLoaded();
return;
}
var script = document.createElement('script');
script.id = 'horizonScript';
var src = host + ':' + port;
if (/ngrok.io/.test(location.hostname)) {
src = location.hostname.replace('seats', 'horizon');
}
script.src = '//' + src + '/horizon/horizon.js';
document.head.appendChild(script);
script.onload = scriptLoaded;
},
_computeHorizon: function (host, port) {
var hostString = host + ':' + port;
if (/ngrok.io/.test(location.hostname)) {
hostString = location.hostname.replace('seats', 'horizon');
}
return Horizon({
host: hostString
});
},
detached: function () {
window.removeEventListener(this._eventName, this._libLoadedHandler);
}
};
</script>