通过Websocket更新Polymer组件? [英] Updating Polymer component via Websocket?

查看:72
本文介绍了通过Websocket更新Polymer组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

提前谢谢

/ Robert

推荐答案

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

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();
        }
    })

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

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.

这篇关于通过Websocket更新Polymer组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆