通过Websocket更新Polymer组件?

Rob*_*ldt 13 javascript sockets polymer

我想找到最简单的方法(最好不依赖于很多额外的库)来连接Polymer组件和Web套接字,以便我可以从后端轻松更新它.

现在我已经调查了使用bacon.js这样做,因为很容易直接从Web套接字设置事件流.我的想法是过滤这些消息并将它们路由到单个Polymer组件.但是,如果没有bacon.js或其他库(即只使用Polymer本身和普通的javascript Web套接字)可以轻松完成这项工作,那么这可能更合适.任何想法,提示或示例代码?

提前致谢

/罗伯特·

Mar*_*wan 3

这是使用聚合物处理 websocket 的非常基本的方法

    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();
        }
    })
Run Code Online (Sandbox Code Playgroud)

请看一下WebSocket Polymer Element,Polymer 元素使用当今大多数现代浏览器附带的本机 WebSocket 客户端。