Updating Polymer component via Websocket?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 18:30:16

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26176977/updating-polymer-component-via-websocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!