我正在构建一个 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();
});
});