Skip to content

Instantly share code, notes, and snippets.

@ryuone
Created September 8, 2013 13:19
Show Gist options
  • Save ryuone/6484660 to your computer and use it in GitHub Desktop.
Save ryuone/6484660 to your computer and use it in GitHub Desktop.
// 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 });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment