In this post I will gradually refactor our map framework from how I used to write JavaScript into Backbone.js models, collections, views and events.
Let's start with map load:
locations = []
function load() {
// ...
new Location(35.1800833333, -111.661025, millis, dt['dayMonthDateYear'], dt['time'], dt['full'], 0.0, 'IGNITION_ON');
new Location(35.1801766667, -111.6611183333, millis, dt['dayMonthDateYear'], dt['time'], dt['full'], 1.2427433786685755, 'TIME_WITH_IGNITION_ON');
// repeat 6558 more times..
// ...
}
function Location(lat, lng, timestamp, day, time, complete, speed, event_type, address, rd_info) {
// ...
locations.push(this);
}
$(window).load( load );
We start by moving our array of objects into a Backbone collection.
+class @Locations extends Backbone.Collection
-var locations = []
We then move our object constructor into a Backbone model.
+class @Location extends Backbone.Model
-function Location(lat, lng, timestamp, day, time, complete, speed, event_type, address, rd_info) {
- this.timestamp = timestamp;
- this.day = day;
- this.time = time;
- this.complete = complete;
- this.speed = speed;
- this.event_type = event_type;
We can now replace all of the object constructors with a single collection constructor
+new Locations( #{@trip.to_json} )
- new Location(35.1800833333, -111.661025, millis, dt['dayMonthDateYear'], dt['time'], dt['full'], 0.0, 'IGNITION_ON');
- new Location(35.1801766667, -111.6611183333, millis, dt['dayMonthDateYear'], dt['time'], dt['full'], 1.2427433786685755, 'TIME_WITH_IGNITION_ON');
NOTE: nothing to do with Rails views
+class @LocationListItem extends Backbone.View
+ tagName: 'li'
+
+ render: ->
-Location.prototype.render = function() {
- var html = "<li>";
1. a model may have multiple views observing it
2. view methods are scoped to a view element and a data model
no need to dig into JSON objects
@LocationListItem extends Backbone.View
+ events:
+ 'click a': 'openInfowindow'
Location.prototype.render = function() {
var html = "";
- html += '<a href="javascript:locations[' + this.index + '].openInfowindow()">';
I came from Koding. May I ask, in brief, what the context.purpose of this is? Just so I know better what you require and how.