-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebsocket-sharing-behavior.html
49 lines (47 loc) · 1.44 KB
/
websocket-sharing-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
<!--
Copyright (c) 2018 Willem Burgers. All rights reserved.
This code may only be used under the BSD style license found at http://wburgers.github.io/LICENSE.txt
For a list of Contributors check https://github.com/wburgers/websocket-component/graphs/contributors
-->
<link rel="import" href="../polymer/polymer.html">
<script>
/** @polymerBehavior */
const WebsocketSharingBehavior = subclass => class extends subclass {
static get properties() {
return {
/**
* The socketId is the identifier for the shared socket, if a socket with the given identifier exists it
* will be used, if not, a new one will be created.
*/
socketId: {
type: String
},
/**
* a Map of websockets ( identifier -> WebScoket ) that is shared across all instances
*/
_websockets: {
type: Object,
value: new Map()
}
}
}
/**
* Tries to get an instance of a websocket by the socketId
* If it does not exist it creates a new Websocket
* @param socketId
* @param socketUrl
* @param socketProtocols
*/
getOrCreateSocket(socketUrl, socketProtocols, _socketId) {
const socketId = _socketId | this.socketId;
if (!this._websockets.has(socketId)) {
this._websockets.set(socketId, new WebSocket(socketUrl, socketProtocols));
}
return this._websockets.get(socketId);
}
removeWebsocket(_socketId) {
const socketId = _socketId | this.socketId;
this._websockets.delete(socketId)
}
}
</script>