我找到了解决我自己的问题的方法。再说一次,我是 Backbone 的新手,所以我不确定这是否是最好的方法——我会对这个解决方案是否遵循最佳实践的反馈感兴趣。该代码基于Andrew Cholakian 的这个示例。我保留了一些打印语句,当您运行代码时它们会很有帮助。
该代码假定您的后端以以下形式发送 JSON 数据
{data: "{"lat": latitude, "long": longitude, "amt": amount}"}
// this function opens the websocket and will trigger add_point when
// a new message is received
Stream = function () {
_.extend(this, Backbone.Events);
var self = this;
self.socket = new WebSocket("ws://" + document.domain + ":5000/websocket");
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('add_point', JSON.parse(e.data));
};
self.socket.onclose = function(e) {
self.trigger('close', e);
console.log('socket closed');
};
};
DataPoint = Backbone.Model.extend({
defaults: {
lat: null,
long: null,
amt: null
}
});
DataSet = Backbone.Collection.extend({
model: DataPoint,
initialize: function(options) {
this.stream = options.stream;
var self = this;
this.stream.on("add_point", function(pt) {
self.add( new DataPoint({
lat: pt.lat,
long: pt.long,
amt: pt.amt
}));
console.log('updated collection');
console.log(self.models);
});
}
});
MapView = Backbone.View.extend({
initialize: function(options) {
this.dataSet = options.dataSet;
}
});
$(function() {
var stream = new Stream();
var dataSet = new DataSet({ stream: stream });
var mapView = new MapView({ dataSet: dataSet });
});