我正在构建一个Backbone应用程序,其中Flask / Python服务器通过websocket将纬度和经度数据发送到前端。然后使用D3实时绘制每个位置。我想要一个开始和停止按钮,它将打开和关闭websocket。我无法弄清楚如何关闭websocket。我已经检查过停止按钮实际上是在触发locMap.model.stream.socket.close();.我对Backbone很新,我也不确定我为启动和停止应用程序所写的jQuery应该去哪里。这是我的代码(删除了一些不相关的D3代码):
// Initialize the websocket and wrap it in a Backbone Event
LocationStream = function () {
this.addr = "ws://" + document.domain + ":5000/websocket";
_.extend(this, Backbone.Events);
var self = this;
self.socket = new WebSocket(this.addr);
console.log("Using a standard websocket");
self.socket.onopen = function(e) {
self.trigger('open',e);
console.log('socket opened');
};
self.socket.onerror = function (e) {
self.trigger('error', e);
};
self.socket.onmessage = function (e) {
self.trigger('message', e);
self.trigger('data', e.data);
self.trigger('point', JSON.parse(e.data))
};
self.socket.onclose = function (e) {
self.trigger('close', e);
console.log("socket closed");
};
self.socket.onerror = function (e) {
self.trigger('error', e);
};
};
// Models
// Create a Backbone model to keep track of streaming location data
LocationSequence = Backbone.Model.extend({
initialize: function (opts) {
this.stream = opts.stream;
var self = this;
this.stream.on('point', function (pt) {
var points = self.get('points');
var updated = (new Date()).getTime();
var coordinates = projection([pt.long, pt.lat]);
points.push([updated, coordinates]);
self.set({points: points, last_update: updated});
});
},
defaults: {
points: []
}
});
// Views
// Add a #locations 'g' element to the SVG containing the map of the US
// location points will be appended to this element
var LocationMap = Backbone.View.extend({
initialize: function () {
d3_map.append("svg:g")
.attr("id", "locations");
this.model.on('change', this.render, this);
},
render: function () {
var locations = d3_map.select("#locations").selectAll('circle')
.data(this.model.get('points'),
function (d) { return d[0]; });
locations.enter()
.append("svg:circle")
.attr("id", "circle")
.attr("cy", function(d) { return d[1][1]; })
.attr("cx", function(d) { return d[1][0]; })
.attr("r", 4.5);
},
});
$("#start").click(function () {
var locStream = new LocationStream();
var locations = new LocationSequence({stream: locStream});
var locMap = new LocationMap({model: locations});
console.log("start triggered");
$("#stop").click(function () {
locMap.model.stream.socket.close();
});
});
答案 0 :(得分:0)
我是否密集或不会这样做:
locStream.socket.close();
对不起,我刚看到这个,想知道你是否得到了答案。我没有排名甚至评论,所以我不得不做出这个“回答。”
如果你解决了,请告诉我们!