I want to find the simplest possible way (preferably without relying on a lot of additional libraries) to connect a Polymer ponent with a web socket so that I can update it easily from the backend.
Right now I have investigated doing this with bacon.js since it is very easy to setup a an event stream directly from the web socket. My idea is to filter these messages and route them to individual Polymer ponents. However, if this can be easily done without bacon.js or other libraries (i.e. with only Polymer itself and a normal javascript Web socket) that might be preferable. Any ideas, hints or example code?
Thanks, in advance
/Robert
I want to find the simplest possible way (preferably without relying on a lot of additional libraries) to connect a Polymer ponent with a web socket so that I can update it easily from the backend.
Right now I have investigated doing this with bacon.js since it is very easy to setup a an event stream directly from the web socket. My idea is to filter these messages and route them to individual Polymer ponents. However, if this can be easily done without bacon.js or other libraries (i.e. with only Polymer itself and a normal javascript Web socket) that might be preferable. Any ideas, hints or example code?
Thanks, in advance
/Robert
Share Improve this question asked Oct 3, 2014 at 10:03 Robert FeldtRobert Feldt 1813 silver badges4 bronze badges 1- 2 customelements.io/?q=websocket or searching "socket" on ponent.kitchen returns a couple of results. – ebidel Commented Oct 3, 2014 at 16:31
1 Answer
Reset to default 3Here is a very basic way of handling websocket using polymer
Polymer({
is: "ws-element",
socket: null,
properties: {
protocol: {
type: String
},
url: {
type: String
}
},
ready: function () {
this.socket = new WebSocket(this.url, this.protocol);
this.socket.onerror = this.onError.bind(this);
this.socket.onopen = this.onOpen.bind(this);
this.socket.onmessage = this.onMessage.bind(this);
},
onError: function (error) {
this.fire('onerror', error);
},
onOpen: function (event) {
this.fire('onopen');
},
onMessage: function (event) {
this.fire('onmessage', event.data);
},
send: function (message) {
this.socket.send(message);
},
close: function () {
this.socket.close();
}
})
Please take a look at the WebSocket Polymer Element, The Polymer element uses the native WebSocket client that es with most of today's modern browsers.