我想找到最简单的方法(最好不依赖于许多额外的库)将Polymer组件与web套接字连接,这样我就可以从后端轻松更新它。
现在,我已经研究过使用bacon.js进行此操作,因为直接从web套接字设置事件流非常容易。我的想法是过滤这些信息,并将它们发送到各个聚合物组件。然而,如果这可以在没有bacon.js或其他库的情况下轻松完成(即,只有Polymer本身和一个普通的javascript Web套接字),那可能是更可取的。有什么想法、提示或示例代码吗?
谢谢,提前
/Robert
以下是使用聚合物处理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聚合物元素,聚合物元素使用当今大多数现代浏览器附带的本地WebSocket客户端。