最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Updating Polymer component via Websocket? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论