【问题标题】:Updating Polymer component via Websocket?通过 Websocket 更新 Polymer 组件?
【发布时间】:2014-11-28 09:29:51
【问题描述】:

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

现在我已经研究过使用 bacon.js 来做这件事,因为直接从 Web 套接字设置事件流非常容易。我的想法是过滤这些消息并将它们路由到单个 Polymer 组件。但是,如果这可以在没有 bacon.js 或其他库(即仅使用 Polymer 本身和普通的 javascript Web 套接字)的情况下轻松完成,那可能更可取。有什么想法、提示或示例代码吗?

谢谢,提前

/罗伯特

【问题讨论】:

标签: javascript sockets polymer


【解决方案1】:

这是使用聚合物处理 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();
        }
    })

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

【讨论】:

  • 你为什么要定义socket:null,在属性之外:{}对象?
  • 可能是因为它不是您传递给组件的属性。相反,它是一个私有实例变量。不过我不记得了。
猜你喜欢
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2021-01-07
  • 1970-01-01
  • 2019-02-14
相关资源
最近更新 更多