Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Polymer component via Websocket?

I want to find the simplest possible way (preferably without relying on a lot of additional libraries) to connect a Polymer component 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 components. 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

like image 287
Robert Feldt Avatar asked Oct 03 '14 10:10

Robert Feldt


1 Answers

Here 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 comes with most of today's modern browsers.

like image 156
Marwan Avatar answered Sep 28 '22 06:09

Marwan