helios 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. data/Gemfile.lock +82 -37
  2. data/README.md +16 -0
  3. data/bin/helios +4 -0
  4. data/example/Gemfile +7 -0
  5. data/example/Gemfile.lock +149 -0
  6. data/example/Procfile +1 -0
  7. data/example/Sample.xcdatamodeld/Sample.xcdatamodel/contents +23 -0
  8. data/example/config.ru +6 -0
  9. data/helios.gemspec +17 -7
  10. data/lib/helios.rb +15 -1
  11. data/lib/helios/backend.rb +46 -0
  12. data/lib/helios/backend/data.rb +36 -0
  13. data/lib/helios/backend/in-app-purchase.rb +33 -0
  14. data/lib/helios/backend/passbook.rb +25 -0
  15. data/lib/helios/backend/push-notification.rb +90 -0
  16. data/lib/helios/commands.rb +1 -0
  17. data/lib/helios/commands/new.rb +27 -0
  18. data/lib/helios/frontend.rb +56 -0
  19. data/lib/helios/frontend/images/data.png +0 -0
  20. data/lib/helios/frontend/images/data.svg +1 -0
  21. data/lib/helios/frontend/images/in-app-purchase.png +0 -0
  22. data/lib/helios/frontend/images/in-app-purchase.svg +1 -0
  23. data/lib/helios/frontend/images/passbook.png +0 -0
  24. data/lib/helios/frontend/images/passbook.svg +1 -0
  25. data/lib/helios/frontend/images/push-notification.png +0 -0
  26. data/lib/helios/frontend/images/push-notification.svg +1 -0
  27. data/lib/helios/frontend/javascripts/foundation/foundation.alerts.js +50 -0
  28. data/lib/helios/frontend/javascripts/foundation/foundation.clearing.js +478 -0
  29. data/lib/helios/frontend/javascripts/foundation/foundation.cookie.js +74 -0
  30. data/lib/helios/frontend/javascripts/foundation/foundation.dropdown.js +122 -0
  31. data/lib/helios/frontend/javascripts/foundation/foundation.forms.js +403 -0
  32. data/lib/helios/frontend/javascripts/foundation/foundation.joyride.js +613 -0
  33. data/lib/helios/frontend/javascripts/foundation/foundation.js +331 -0
  34. data/lib/helios/frontend/javascripts/foundation/foundation.magellan.js +130 -0
  35. data/lib/helios/frontend/javascripts/foundation/foundation.orbit.js +355 -0
  36. data/lib/helios/frontend/javascripts/foundation/foundation.placeholder.js +159 -0
  37. data/lib/helios/frontend/javascripts/foundation/foundation.reveal.js +272 -0
  38. data/lib/helios/frontend/javascripts/foundation/foundation.section.js +183 -0
  39. data/lib/helios/frontend/javascripts/foundation/foundation.tooltips.js +195 -0
  40. data/lib/helios/frontend/javascripts/foundation/foundation.topbar.js +208 -0
  41. data/lib/helios/frontend/javascripts/helios.coffee +48 -0
  42. data/lib/helios/frontend/javascripts/helios/collections.coffee +30 -0
  43. data/lib/helios/frontend/javascripts/helios/models.coffee +23 -0
  44. data/lib/helios/frontend/javascripts/helios/router.coffee +52 -0
  45. data/lib/helios/frontend/javascripts/helios/views.coffee +92 -0
  46. data/lib/helios/frontend/javascripts/vendor/backbone.datagrid.js +662 -0
  47. data/lib/helios/frontend/javascripts/vendor/backbone.js +1487 -0
  48. data/lib/helios/frontend/javascripts/vendor/jquery.js +9597 -0
  49. data/lib/helios/frontend/javascripts/vendor/underscore.js +1227 -0
  50. data/lib/helios/frontend/stylesheets/_settings.scss +988 -0
  51. data/lib/helios/frontend/stylesheets/screen.sass +98 -0
  52. data/lib/helios/frontend/templates/data/entities.hbs +7 -0
  53. data/lib/helios/frontend/templates/data/entity.hbs +17 -0
  54. data/lib/helios/frontend/templates/in-app-purchase/receipt.hbs +53 -0
  55. data/lib/helios/frontend/templates/in-app-purchase/receipts.hbs +39 -0
  56. data/lib/helios/frontend/templates/passbook/passes.hbs +25 -0
  57. data/lib/helios/frontend/templates/push-notification/device.hbs +35 -0
  58. data/lib/helios/frontend/templates/push-notification/devices.hbs +37 -0
  59. data/lib/helios/frontend/views/devices.jst.tpl +3 -0
  60. data/lib/helios/frontend/views/entities.jst.tpl +9 -0
  61. data/lib/helios/frontend/views/index.haml +30 -0
  62. data/lib/helios/frontend/views/passes.jst.tpl +3 -0
  63. data/lib/helios/frontend/views/receipts.jst.tpl +3 -0
  64. data/lib/helios/templates/Gemfile.erb +7 -0
  65. data/lib/helios/templates/Procfile.erb +1 -0
  66. data/lib/helios/templates/README.md.erb +9 -0
  67. data/lib/helios/templates/config.ru.erb +6 -0
  68. data/lib/helios/version.rb +3 -0
  69. metadata +199 -26
@@ -0,0 +1,1487 @@
1
+ // Backbone.js
2
+ // ===========
3
+
4
+ // > (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
5
+ // > Backbone may be freely distributed under the MIT license.
6
+ // > For all details and documentation: http://backbonejs.org
7
+
8
+ // Initial Setup
9
+ // -------------
10
+
11
+ (function(){
12
+
13
+ // Save a reference to the global object (`window` in the browser, `exports`
14
+ // on the server).
15
+ var root = this;
16
+
17
+ // Save the previous value of the `Backbone` variable, so that it can be
18
+ // restored later on, if `noConflict` is used.
19
+ var previousBackbone = root.Backbone;
20
+
21
+ // Create a local reference to array methods.
22
+ var array = [];
23
+ var push = array.push;
24
+ var slice = array.slice;
25
+ var splice = array.splice;
26
+
27
+ // The top-level namespace. All public Backbone classes and modules will
28
+ // be attached to this. Exported for both CommonJS and the browser.
29
+ var Backbone;
30
+ if (typeof exports !== 'undefined') {
31
+ Backbone = exports;
32
+ } else {
33
+ Backbone = root.Backbone = {};
34
+ }
35
+
36
+ // Current version of the library. Keep in sync with `package.json`.
37
+ Backbone.VERSION = '0.9.10';
38
+
39
+ // Require Underscore, if we're on the server, and it's not already present.
40
+ var _ = root._;
41
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
42
+
43
+ // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
44
+ Backbone.$ = root.jQuery || root.Zepto || root.ender;
45
+
46
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
47
+ // to its previous owner. Returns a reference to this Backbone object.
48
+ Backbone.noConflict = function() {
49
+ root.Backbone = previousBackbone;
50
+ return this;
51
+ };
52
+
53
+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
54
+ // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
55
+ // set a `X-Http-Method-Override` header.
56
+ Backbone.emulateHTTP = false;
57
+
58
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
59
+ // `application/json` requests ... will encode the body as
60
+ // `application/x-www-form-urlencoded` instead and will send the model in a
61
+ // form param named `model`.
62
+ Backbone.emulateJSON = false;
63
+
64
+ // Backbone.Events
65
+ // ---------------
66
+
67
+ // Regular expression used to split event strings.
68
+ var eventSplitter = /\s+/;
69
+
70
+ // Implement fancy features of the Events API such as multiple event
71
+ // names `"change blur"` and jQuery-style event maps `{change: action}`
72
+ // in terms of the existing API.
73
+ var eventsApi = function(obj, action, name, rest) {
74
+ if (!name) return true;
75
+ if (typeof name === 'object') {
76
+ for (var key in name) {
77
+ obj[action].apply(obj, [key, name[key]].concat(rest));
78
+ }
79
+ } else if (eventSplitter.test(name)) {
80
+ var names = name.split(eventSplitter);
81
+ for (var i = 0, l = names.length; i < l; i++) {
82
+ obj[action].apply(obj, [names[i]].concat(rest));
83
+ }
84
+ } else {
85
+ return true;
86
+ }
87
+ };
88
+
89
+ // Optimized internal dispatch function for triggering events. Tries to
90
+ // keep the usual cases speedy (most Backbone events have 3 arguments).
91
+ var triggerEvents = function(events, args) {
92
+ var ev, i = -1, l = events.length;
93
+ switch (args.length) {
94
+ case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
95
+ return;
96
+ case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]);
97
+ return;
98
+ case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]);
99
+ return;
100
+ case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]);
101
+ return;
102
+ default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
103
+ }
104
+ };
105
+
106
+ // A module that can be mixed in to *any object* in order to provide it with
107
+ // custom events. You may bind with `on` or remove with `off` callback
108
+ // functions to an event; `trigger`-ing an event fires all callbacks in
109
+ // succession.
110
+ var Events = Backbone.Events = {
111
+
112
+ // Bind one or more space separated events, or an events map,
113
+ // to a `callback` function. Passing `"all"` will bind the callback to
114
+ // all events fired.
115
+ on: function(name, callback, context) {
116
+ if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this;
117
+ this._events || (this._events = {});
118
+ var list = this._events[name] || (this._events[name] = []);
119
+ list.push({callback: callback, context: context, ctx: context || this});
120
+ return this;
121
+ },
122
+
123
+ // Bind events to only be triggered a single time. After the first time
124
+ // the callback is invoked, it will be removed.
125
+ once: function(name, callback, context) {
126
+ if (!(eventsApi(this, 'once', name, [callback, context]) && callback)) return this;
127
+ var self = this;
128
+ var once = _.once(function() {
129
+ self.off(name, once);
130
+ callback.apply(this, arguments);
131
+ });
132
+ once._callback = callback;
133
+ this.on(name, once, context);
134
+ return this;
135
+ },
136
+
137
+ // Remove one or many callbacks. If `context` is null, removes all
138
+ // callbacks with that function. If `callback` is null, removes all
139
+ // callbacks for the event. If `name` is null, removes all bound
140
+ // callbacks for all events.
141
+ off: function(name, callback, context) {
142
+ var list, ev, events, names, i, l, j, k;
143
+ if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
144
+ if (!name && !callback && !context) {
145
+ this._events = {};
146
+ return this;
147
+ }
148
+
149
+ names = name ? [name] : _.keys(this._events);
150
+ for (i = 0, l = names.length; i < l; i++) {
151
+ name = names[i];
152
+ if (list = this._events[name]) {
153
+ events = [];
154
+ if (callback || context) {
155
+ for (j = 0, k = list.length; j < k; j++) {
156
+ ev = list[j];
157
+ if ((callback && callback !== ev.callback &&
158
+ callback !== ev.callback._callback) ||
159
+ (context && context !== ev.context)) {
160
+ events.push(ev);
161
+ }
162
+ }
163
+ }
164
+ this._events[name] = events;
165
+ }
166
+ }
167
+
168
+ return this;
169
+ },
170
+
171
+ // Trigger one or many events, firing all bound callbacks. Callbacks are
172
+ // passed the same arguments as `trigger` is, apart from the event name
173
+ // (unless you're listening on `"all"`, which will cause your callback to
174
+ // receive the true name of the event as the first argument).
175
+ trigger: function(name) {
176
+ if (!this._events) return this;
177
+ var args = slice.call(arguments, 1);
178
+ if (!eventsApi(this, 'trigger', name, args)) return this;
179
+ var events = this._events[name];
180
+ var allEvents = this._events.all;
181
+ if (events) triggerEvents(events, args);
182
+ if (allEvents) triggerEvents(allEvents, arguments);
183
+ return this;
184
+ },
185
+
186
+ // An inversion-of-control version of `on`. Tell *this* object to listen to
187
+ // an event in another object ... keeping track of what it's listening to.
188
+ listenTo: function(obj, name, callback) {
189
+ var listeners = this._listeners || (this._listeners = {});
190
+ var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
191
+ listeners[id] = obj;
192
+ obj.on(name, typeof name === 'object' ? this : callback, this);
193
+ return this;
194
+ },
195
+
196
+ // Tell this object to stop listening to either specific events ... or
197
+ // to every object it's currently listening to.
198
+ stopListening: function(obj, name, callback) {
199
+ var listeners = this._listeners;
200
+ if (!listeners) return;
201
+ if (obj) {
202
+ obj.off(name, typeof name === 'object' ? this : callback, this);
203
+ if (!name && !callback) delete listeners[obj._listenerId];
204
+ } else {
205
+ if (typeof name === 'object') callback = this;
206
+ for (var id in listeners) {
207
+ listeners[id].off(name, callback, this);
208
+ }
209
+ this._listeners = {};
210
+ }
211
+ return this;
212
+ }
213
+ };
214
+
215
+ // Aliases for backwards compatibility.
216
+ Events.bind = Events.on;
217
+ Events.unbind = Events.off;
218
+
219
+ // Allow the `Backbone` object to serve as a global event bus, for folks who
220
+ // want global "pubsub" in a convenient place.
221
+ _.extend(Backbone, Events);
222
+
223
+ // Backbone.Model
224
+ // --------------
225
+
226
+ // Create a new model, with defined attributes. A client id (`cid`)
227
+ // is automatically generated and assigned for you.
228
+ var Model = Backbone.Model = function(attributes, options) {
229
+ var defaults;
230
+ var attrs = attributes || {};
231
+ this.cid = _.uniqueId('c');
232
+ this.attributes = {};
233
+ if (options && options.collection) this.collection = options.collection;
234
+ if (options && options.parse) attrs = this.parse(attrs, options) || {};
235
+ if (defaults = _.result(this, 'defaults')) {
236
+ attrs = _.defaults({}, attrs, defaults);
237
+ }
238
+ this.set(attrs, options);
239
+ this.changed = {};
240
+ this.initialize.apply(this, arguments);
241
+ };
242
+
243
+ // Attach all inheritable methods to the Model prototype.
244
+ _.extend(Model.prototype, Events, {
245
+
246
+ // A hash of attributes whose current and previous value differ.
247
+ changed: null,
248
+
249
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
250
+ // CouchDB users may want to set this to `"_id"`.
251
+ idAttribute: 'id',
252
+
253
+ // Initialize is an empty function by default. Override it with your own
254
+ // initialization logic.
255
+ initialize: function(){},
256
+
257
+ // Return a copy of the model's `attributes` object.
258
+ toJSON: function(options) {
259
+ return _.clone(this.attributes);
260
+ },
261
+
262
+ // Proxy `Backbone.sync` by default.
263
+ sync: function() {
264
+ return Backbone.sync.apply(this, arguments);
265
+ },
266
+
267
+ // Get the value of an attribute.
268
+ get: function(attr) {
269
+ return this.attributes[attr];
270
+ },
271
+
272
+ // Get the HTML-escaped value of an attribute.
273
+ escape: function(attr) {
274
+ return _.escape(this.get(attr));
275
+ },
276
+
277
+ // Returns `true` if the attribute contains a value that is not null
278
+ // or undefined.
279
+ has: function(attr) {
280
+ return this.get(attr) != null;
281
+ },
282
+
283
+ // ----------------------------------------------------------------------
284
+
285
+ // Set a hash of model attributes on the object, firing `"change"` unless
286
+ // you choose to silence it.
287
+ set: function(key, val, options) {
288
+ var attr, attrs, unset, changes, silent, changing, prev, current;
289
+ if (key == null) return this;
290
+
291
+ // Handle both `"key", value` and `{key: value}` -style arguments.
292
+ if (typeof key === 'object') {
293
+ attrs = key;
294
+ options = val;
295
+ } else {
296
+ (attrs = {})[key] = val;
297
+ }
298
+
299
+ options || (options = {});
300
+
301
+ // Run validation.
302
+ if (!this._validate(attrs, options)) return false;
303
+
304
+ // Extract attributes and options.
305
+ unset = options.unset;
306
+ silent = options.silent;
307
+ changes = [];
308
+ changing = this._changing;
309
+ this._changing = true;
310
+
311
+ if (!changing) {
312
+ this._previousAttributes = _.clone(this.attributes);
313
+ this.changed = {};
314
+ }
315
+ current = this.attributes, prev = this._previousAttributes;
316
+
317
+ // Check for changes of `id`.
318
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
319
+
320
+ // For each `set` attribute, update or delete the current value.
321
+ for (attr in attrs) {
322
+ val = attrs[attr];
323
+ if (!_.isEqual(current[attr], val)) changes.push(attr);
324
+ if (!_.isEqual(prev[attr], val)) {
325
+ this.changed[attr] = val;
326
+ } else {
327
+ delete this.changed[attr];
328
+ }
329
+ unset ? delete current[attr] : current[attr] = val;
330
+ }
331
+
332
+ // Trigger all relevant attribute changes.
333
+ if (!silent) {
334
+ if (changes.length) this._pending = true;
335
+ for (var i = 0, l = changes.length; i < l; i++) {
336
+ this.trigger('change:' + changes[i], this, current[changes[i]], options);
337
+ }
338
+ }
339
+
340
+ if (changing) return this;
341
+ if (!silent) {
342
+ while (this._pending) {
343
+ this._pending = false;
344
+ this.trigger('change', this, options);
345
+ }
346
+ }
347
+ this._pending = false;
348
+ this._changing = false;
349
+ return this;
350
+ },
351
+
352
+ // Remove an attribute from the model, firing `"change"` unless you choose
353
+ // to silence it. `unset` is a noop if the attribute doesn't exist.
354
+ unset: function(attr, options) {
355
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
356
+ },
357
+
358
+ // Clear all attributes on the model, firing `"change"` unless you choose
359
+ // to silence it.
360
+ clear: function(options) {
361
+ var attrs = {};
362
+ for (var key in this.attributes) attrs[key] = void 0;
363
+ return this.set(attrs, _.extend({}, options, {unset: true}));
364
+ },
365
+
366
+ // Determine if the model has changed since the last `"change"` event.
367
+ // If you specify an attribute name, determine if that attribute has changed.
368
+ hasChanged: function(attr) {
369
+ if (attr == null) return !_.isEmpty(this.changed);
370
+ return _.has(this.changed, attr);
371
+ },
372
+
373
+ // Return an object containing all the attributes that have changed, or
374
+ // false if there are no changed attributes. Useful for determining what
375
+ // parts of a view need to be updated and/or what attributes need to be
376
+ // persisted to the server. Unset attributes will be set to undefined.
377
+ // You can also pass an attributes object to diff against the model,
378
+ // determining if there *would be* a change.
379
+ changedAttributes: function(diff) {
380
+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
381
+ var val, changed = false;
382
+ var old = this._changing ? this._previousAttributes : this.attributes;
383
+ for (var attr in diff) {
384
+ if (_.isEqual(old[attr], (val = diff[attr]))) continue;
385
+ (changed || (changed = {}))[attr] = val;
386
+ }
387
+ return changed;
388
+ },
389
+
390
+ // Get the previous value of an attribute, recorded at the time the last
391
+ // `"change"` event was fired.
392
+ previous: function(attr) {
393
+ if (attr == null || !this._previousAttributes) return null;
394
+ return this._previousAttributes[attr];
395
+ },
396
+
397
+ // Get all of the attributes of the model at the time of the previous
398
+ // `"change"` event.
399
+ previousAttributes: function() {
400
+ return _.clone(this._previousAttributes);
401
+ },
402
+
403
+ // ---------------------------------------------------------------------
404
+
405
+ // Fetch the model from the server. If the server's representation of the
406
+ // model differs from its current attributes, they will be overriden,
407
+ // triggering a `"change"` event.
408
+ fetch: function(options) {
409
+ options = options ? _.clone(options) : {};
410
+ if (options.parse === void 0) options.parse = true;
411
+ var success = options.success;
412
+ options.success = function(model, resp, options) {
413
+ if (!model.set(model.parse(resp, options), options)) return false;
414
+ if (success) success(model, resp, options);
415
+ };
416
+ return this.sync('read', this, options);
417
+ },
418
+
419
+ // Set a hash of model attributes, and sync the model to the server.
420
+ // If the server returns an attributes hash that differs, the model's
421
+ // state will be `set` again.
422
+ save: function(key, val, options) {
423
+ var attrs, success, method, xhr, attributes = this.attributes;
424
+
425
+ // Handle both `"key", value` and `{key: value}` -style arguments.
426
+ if (key == null || typeof key === 'object') {
427
+ attrs = key;
428
+ options = val;
429
+ } else {
430
+ (attrs = {})[key] = val;
431
+ }
432
+
433
+ // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
434
+ if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
435
+
436
+ options = _.extend({validate: true}, options);
437
+
438
+ // Do not persist invalid models.
439
+ if (!this._validate(attrs, options)) return false;
440
+
441
+ // Set temporary attributes if `{wait: true}`.
442
+ if (attrs && options.wait) {
443
+ this.attributes = _.extend({}, attributes, attrs);
444
+ }
445
+
446
+ // After a successful server-side save, the client is (optionally)
447
+ // updated with the server-side state.
448
+ if (options.parse === void 0) options.parse = true;
449
+ success = options.success;
450
+ options.success = function(model, resp, options) {
451
+ // Ensure attributes are restored during synchronous saves.
452
+ model.attributes = attributes;
453
+ var serverAttrs = model.parse(resp, options);
454
+ if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
455
+ if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
456
+ return false;
457
+ }
458
+ if (success) success(model, resp, options);
459
+ };
460
+
461
+ // Finish configuring and sending the Ajax request.
462
+ method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
463
+ if (method === 'patch') options.attrs = attrs;
464
+ xhr = this.sync(method, this, options);
465
+
466
+ // Restore attributes.
467
+ if (attrs && options.wait) this.attributes = attributes;
468
+
469
+ return xhr;
470
+ },
471
+
472
+ // Destroy this model on the server if it was already persisted.
473
+ // Optimistically removes the model from its collection, if it has one.
474
+ // If `wait: true` is passed, waits for the server to respond before removal.
475
+ destroy: function(options) {
476
+ options = options ? _.clone(options) : {};
477
+ var model = this;
478
+ var success = options.success;
479
+
480
+ var destroy = function() {
481
+ model.trigger('destroy', model, model.collection, options);
482
+ };
483
+
484
+ options.success = function(model, resp, options) {
485
+ if (options.wait || model.isNew()) destroy();
486
+ if (success) success(model, resp, options);
487
+ };
488
+
489
+ if (this.isNew()) {
490
+ options.success(this, null, options);
491
+ return false;
492
+ }
493
+
494
+ var xhr = this.sync('delete', this, options);
495
+ if (!options.wait) destroy();
496
+ return xhr;
497
+ },
498
+
499
+ // Default URL for the model's representation on the server -- if you're
500
+ // using Backbone's restful methods, override this to change the endpoint
501
+ // that will be called.
502
+ url: function() {
503
+ var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
504
+ if (this.isNew()) return base;
505
+ return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
506
+ },
507
+
508
+ // **parse** converts a response into the hash of attributes to be `set` on
509
+ // the model. The default implementation is just to pass the response along.
510
+ parse: function(resp, options) {
511
+ return resp;
512
+ },
513
+
514
+ // Create a new model with identical attributes to this one.
515
+ clone: function() {
516
+ return new this.constructor(this.attributes);
517
+ },
518
+
519
+ // A model is new if it has never been saved to the server, and lacks an id.
520
+ isNew: function() {
521
+ return this.id == null;
522
+ },
523
+
524
+ // Check if the model is currently in a valid state.
525
+ isValid: function(options) {
526
+ return !this.validate || !this.validate(this.attributes, options);
527
+ },
528
+
529
+ // Run validation against the next complete set of model attributes,
530
+ // returning `true` if all is well. Otherwise, fire a general
531
+ // `"error"` event and call the error callback, if specified.
532
+ _validate: function(attrs, options) {
533
+ if (!options.validate || !this.validate) return true;
534
+ attrs = _.extend({}, this.attributes, attrs);
535
+ var error = this.validationError = this.validate(attrs, options) || null;
536
+ if (!error) return true;
537
+ this.trigger('invalid', this, error, options || {});
538
+ return false;
539
+ }
540
+
541
+ });
542
+
543
+ // Backbone.Collection
544
+ // -------------------
545
+
546
+ // Provides a standard collection class for our sets of models, ordered
547
+ // or unordered. If a `comparator` is specified, the Collection will maintain
548
+ // its models in sort order, as they're added and removed.
549
+ var Collection = Backbone.Collection = function(models, options) {
550
+ options || (options = {});
551
+ if (options.model) this.model = options.model;
552
+ if (options.comparator !== void 0) this.comparator = options.comparator;
553
+ this.models = [];
554
+ this._reset();
555
+ this.initialize.apply(this, arguments);
556
+ if (models) this.reset(models, _.extend({silent: true}, options));
557
+ };
558
+
559
+ // Define the Collection's inheritable methods.
560
+ _.extend(Collection.prototype, Events, {
561
+
562
+ // The default model for a collection is just a **Backbone.Model**.
563
+ // This should be overridden in most cases.
564
+ model: Model,
565
+
566
+ // Initialize is an empty function by default. Override it with your own
567
+ // initialization logic.
568
+ initialize: function(){},
569
+
570
+ // The JSON representation of a Collection is an array of the
571
+ // models' attributes.
572
+ toJSON: function(options) {
573
+ return this.map(function(model){ return model.toJSON(options); });
574
+ },
575
+
576
+ // Proxy `Backbone.sync` by default.
577
+ sync: function() {
578
+ return Backbone.sync.apply(this, arguments);
579
+ },
580
+
581
+ // Add a model, or list of models to the set.
582
+ add: function(models, options) {
583
+ models = _.isArray(models) ? models.slice() : [models];
584
+ options || (options = {});
585
+ var i, l, model, attrs, existing, doSort, add, at, sort, sortAttr;
586
+ add = [];
587
+ at = options.at;
588
+ sort = this.comparator && (at == null) && options.sort != false;
589
+ sortAttr = _.isString(this.comparator) ? this.comparator : null;
590
+
591
+ // Turn bare objects into model references, and prevent invalid models
592
+ // from being added.
593
+ for (i = 0, l = models.length; i < l; i++) {
594
+ if (!(model = this._prepareModel(attrs = models[i], options))) {
595
+ this.trigger('invalid', this, attrs, options);
596
+ continue;
597
+ }
598
+
599
+ // If a duplicate is found, prevent it from being added and
600
+ // optionally merge it into the existing model.
601
+ if (existing = this.get(model)) {
602
+ if (options.merge) {
603
+ existing.set(attrs === model ? model.attributes : attrs, options);
604
+ if (sort && !doSort && existing.hasChanged(sortAttr)) doSort = true;
605
+ }
606
+ continue;
607
+ }
608
+
609
+ // This is a new model, push it to the `add` list.
610
+ add.push(model);
611
+
612
+ // Listen to added models' events, and index models for lookup by
613
+ // `id` and by `cid`.
614
+ model.on('all', this._onModelEvent, this);
615
+ this._byId[model.cid] = model;
616
+ if (model.id != null) this._byId[model.id] = model;
617
+ }
618
+
619
+ // See if sorting is needed, update `length` and splice in new models.
620
+ if (add.length) {
621
+ if (sort) doSort = true;
622
+ this.length += add.length;
623
+ if (at != null) {
624
+ splice.apply(this.models, [at, 0].concat(add));
625
+ } else {
626
+ push.apply(this.models, add);
627
+ }
628
+ }
629
+
630
+ // Silently sort the collection if appropriate.
631
+ if (doSort) this.sort({silent: true});
632
+
633
+ if (options.silent) return this;
634
+
635
+ // Trigger `add` events.
636
+ for (i = 0, l = add.length; i < l; i++) {
637
+ (model = add[i]).trigger('add', model, this, options);
638
+ }
639
+
640
+ // Trigger `sort` if the collection was sorted.
641
+ if (doSort) this.trigger('sort', this, options);
642
+
643
+ return this;
644
+ },
645
+
646
+ // Remove a model, or a list of models from the set.
647
+ remove: function(models, options) {
648
+ models = _.isArray(models) ? models.slice() : [models];
649
+ options || (options = {});
650
+ var i, l, index, model;
651
+ for (i = 0, l = models.length; i < l; i++) {
652
+ model = this.get(models[i]);
653
+ if (!model) continue;
654
+ delete this._byId[model.id];
655
+ delete this._byId[model.cid];
656
+ index = this.indexOf(model);
657
+ this.models.splice(index, 1);
658
+ this.length--;
659
+ if (!options.silent) {
660
+ options.index = index;
661
+ model.trigger('remove', model, this, options);
662
+ }
663
+ this._removeReference(model);
664
+ }
665
+ return this;
666
+ },
667
+
668
+ // Add a model to the end of the collection.
669
+ push: function(model, options) {
670
+ model = this._prepareModel(model, options);
671
+ this.add(model, _.extend({at: this.length}, options));
672
+ return model;
673
+ },
674
+
675
+ // Remove a model from the end of the collection.
676
+ pop: function(options) {
677
+ var model = this.at(this.length - 1);
678
+ this.remove(model, options);
679
+ return model;
680
+ },
681
+
682
+ // Add a model to the beginning of the collection.
683
+ unshift: function(model, options) {
684
+ model = this._prepareModel(model, options);
685
+ this.add(model, _.extend({at: 0}, options));
686
+ return model;
687
+ },
688
+
689
+ // Remove a model from the beginning of the collection.
690
+ shift: function(options) {
691
+ var model = this.at(0);
692
+ this.remove(model, options);
693
+ return model;
694
+ },
695
+
696
+ // Slice out a sub-array of models from the collection.
697
+ slice: function(begin, end) {
698
+ return this.models.slice(begin, end);
699
+ },
700
+
701
+ // Get a model from the set by id.
702
+ get: function(obj) {
703
+ if (obj == null) return void 0;
704
+ this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
705
+ return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
706
+ },
707
+
708
+ // Get the model at the given index.
709
+ at: function(index) {
710
+ return this.models[index];
711
+ },
712
+
713
+ // Return models with matching attributes. Useful for simple cases of `filter`.
714
+ where: function(attrs) {
715
+ if (_.isEmpty(attrs)) return [];
716
+ return this.filter(function(model) {
717
+ for (var key in attrs) {
718
+ if (attrs[key] !== model.get(key)) return false;
719
+ }
720
+ return true;
721
+ });
722
+ },
723
+
724
+ // Force the collection to re-sort itself. You don't need to call this under
725
+ // normal circumstances, as the set will maintain sort order as each item
726
+ // is added.
727
+ sort: function(options) {
728
+ if (!this.comparator) {
729
+ throw new Error('Cannot sort a set without a comparator');
730
+ }
731
+ options || (options = {});
732
+
733
+ // Run sort based on type of `comparator`.
734
+ if (_.isString(this.comparator) || this.comparator.length === 1) {
735
+ this.models = this.sortBy(this.comparator, this);
736
+ } else {
737
+ this.models.sort(_.bind(this.comparator, this));
738
+ }
739
+
740
+ if (!options.silent) this.trigger('sort', this, options);
741
+ return this;
742
+ },
743
+
744
+ // Pluck an attribute from each model in the collection.
745
+ pluck: function(attr) {
746
+ return _.invoke(this.models, 'get', attr);
747
+ },
748
+
749
+ // Smartly update a collection with a change set of models, adding,
750
+ // removing, and merging as necessary.
751
+ update: function(models, options) {
752
+ options = _.extend({add: true, merge: true, remove: true}, options);
753
+ if (options.parse) models = this.parse(models, options);
754
+ var model, i, l, existing;
755
+ var add = [], remove = [], modelMap = {};
756
+
757
+ // Allow a single model (or no argument) to be passed.
758
+ if (!_.isArray(models)) models = models ? [models] : [];
759
+
760
+ // Proxy to `add` for this case, no need to iterate...
761
+ if (options.add && !options.remove) return this.add(models, options);
762
+
763
+ // Determine which models to add and merge, and which to remove.
764
+ for (i = 0, l = models.length; i < l; i++) {
765
+ model = models[i];
766
+ existing = this.get(model);
767
+ if (options.remove && existing) modelMap[existing.cid] = true;
768
+ if ((options.add && !existing) || (options.merge && existing)) {
769
+ add.push(model);
770
+ }
771
+ }
772
+ if (options.remove) {
773
+ for (i = 0, l = this.models.length; i < l; i++) {
774
+ model = this.models[i];
775
+ if (!modelMap[model.cid]) remove.push(model);
776
+ }
777
+ }
778
+
779
+ // Remove models (if applicable) before we add and merge the rest.
780
+ if (remove.length) this.remove(remove, options);
781
+ if (add.length) this.add(add, options);
782
+ return this;
783
+ },
784
+
785
+ // When you have more items than you want to add or remove individually,
786
+ // you can reset the entire set with a new list of models, without firing
787
+ // any `add` or `remove` events. Fires `reset` when finished.
788
+ reset: function(models, options) {
789
+ options || (options = {});
790
+ if (options.parse) models = this.parse(models, options);
791
+ for (var i = 0, l = this.models.length; i < l; i++) {
792
+ this._removeReference(this.models[i]);
793
+ }
794
+ options.previousModels = this.models.slice();
795
+ this._reset();
796
+ if (models) this.add(models, _.extend({silent: true}, options));
797
+ if (!options.silent) this.trigger('reset', this, options);
798
+ return this;
799
+ },
800
+
801
+ // Fetch the default set of models for this collection, resetting the
802
+ // collection when they arrive. If `update: true` is passed, the response
803
+ // data will be passed through the `update` method instead of `reset`.
804
+ fetch: function(options) {
805
+ options = options ? _.clone(options) : {};
806
+ if (options.parse === void 0) options.parse = true;
807
+ var success = options.success;
808
+ options.success = function(collection, resp, options) {
809
+ var method = options.update ? 'update' : 'reset';
810
+ collection[method](resp, options);
811
+ if (success) success(collection, resp, options);
812
+ };
813
+ return this.sync('read', this, options);
814
+ },
815
+
816
+ // Create a new instance of a model in this collection. Add the model to the
817
+ // collection immediately, unless `wait: true` is passed, in which case we
818
+ // wait for the server to agree.
819
+ create: function(model, options) {
820
+ options = options ? _.clone(options) : {};
821
+ if (!(model = this._prepareModel(model, options))) return false;
822
+ if (!options.wait) this.add(model, options);
823
+ var collection = this;
824
+ var success = options.success;
825
+ options.success = function(model, resp, options) {
826
+ if (options.wait) collection.add(model, options);
827
+ if (success) success(model, resp, options);
828
+ };
829
+ model.save(null, options);
830
+ return model;
831
+ },
832
+
833
+ // **parse** converts a response into a list of models to be added to the
834
+ // collection. The default implementation is just to pass it through.
835
+ parse: function(resp, options) {
836
+ return resp;
837
+ },
838
+
839
+ // Create a new collection with an identical list of models as this one.
840
+ clone: function() {
841
+ return new this.constructor(this.models);
842
+ },
843
+
844
+ // Reset all internal state. Called when the collection is reset.
845
+ _reset: function() {
846
+ this.length = 0;
847
+ this.models.length = 0;
848
+ this._byId = {};
849
+ },
850
+
851
+ // Prepare a model or hash of attributes to be added to this collection.
852
+ _prepareModel: function(attrs, options) {
853
+ if (attrs instanceof Model) {
854
+ if (!attrs.collection) attrs.collection = this;
855
+ return attrs;
856
+ }
857
+ options || (options = {});
858
+ options.collection = this;
859
+ var model = new this.model(attrs, options);
860
+ if (!model._validate(attrs, options)) return false;
861
+ return model;
862
+ },
863
+
864
+ // Internal method to remove a model's ties to a collection.
865
+ _removeReference: function(model) {
866
+ if (this === model.collection) delete model.collection;
867
+ model.off('all', this._onModelEvent, this);
868
+ },
869
+
870
+ // Internal method called every time a model in the set fires an event.
871
+ // Sets need to update their indexes when models change ids. All other
872
+ // events simply proxy through. "add" and "remove" events that originate
873
+ // in other collections are ignored.
874
+ _onModelEvent: function(event, model, collection, options) {
875
+ if ((event === 'add' || event === 'remove') && collection !== this) return;
876
+ if (event === 'destroy') this.remove(model, options);
877
+ if (model && event === 'change:' + model.idAttribute) {
878
+ delete this._byId[model.previous(model.idAttribute)];
879
+ if (model.id != null) this._byId[model.id] = model;
880
+ }
881
+ this.trigger.apply(this, arguments);
882
+ },
883
+
884
+ sortedIndex: function (model, value, context) {
885
+ value || (value = this.comparator);
886
+ var iterator = _.isFunction(value) ? value : function(model) {
887
+ return model.get(value);
888
+ };
889
+ return _.sortedIndex(this.models, model, iterator, context);
890
+ }
891
+
892
+ });
893
+
894
+ // Underscore methods that we want to implement on the Collection.
895
+ var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
896
+ 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
897
+ 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
898
+ 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
899
+ 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
900
+ 'isEmpty', 'chain'];
901
+
902
+ // Mix in each Underscore method as a proxy to `Collection#models`.
903
+ _.each(methods, function(method) {
904
+ Collection.prototype[method] = function() {
905
+ var args = slice.call(arguments);
906
+ args.unshift(this.models);
907
+ return _[method].apply(_, args);
908
+ };
909
+ });
910
+
911
+ // Underscore methods that take a property name as an argument.
912
+ var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
913
+
914
+ // Use attributes instead of properties.
915
+ _.each(attributeMethods, function(method) {
916
+ Collection.prototype[method] = function(value, context) {
917
+ var iterator = _.isFunction(value) ? value : function(model) {
918
+ return model.get(value);
919
+ };
920
+ return _[method](this.models, iterator, context);
921
+ };
922
+ });
923
+
924
+ // Backbone.Router
925
+ // ---------------
926
+
927
+ // Routers map faux-URLs to actions, and fire events when routes are
928
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
929
+ var Router = Backbone.Router = function(options) {
930
+ options || (options = {});
931
+ if (options.routes) this.routes = options.routes;
932
+ this._bindRoutes();
933
+ this.initialize.apply(this, arguments);
934
+ };
935
+
936
+ // Cached regular expressions for matching named param parts and splatted
937
+ // parts of route strings.
938
+ var optionalParam = /\((.*?)\)/g;
939
+ var namedParam = /(\(\?)?:\w+/g;
940
+ var splatParam = /\*\w+/g;
941
+ var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
942
+
943
+ // Set up all inheritable **Backbone.Router** properties and methods.
944
+ _.extend(Router.prototype, Events, {
945
+
946
+ // Initialize is an empty function by default. Override it with your own
947
+ // initialization logic.
948
+ initialize: function(){},
949
+
950
+ // Manually bind a single named route to a callback function.
951
+ route: function(route, name, callback) {
952
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
953
+ if (!callback) callback = this[name];
954
+ Backbone.history.route(route, _.bind(function(fragment) {
955
+ var args = this._extractParameters(route, fragment);
956
+ callback && callback.apply(this, args);
957
+ this.trigger.apply(this, ['route:' + name].concat(args));
958
+ this.trigger('route', name, args);
959
+ Backbone.history.trigger('route', this, name, args);
960
+ }, this));
961
+ return this;
962
+ },
963
+
964
+ // Simple proxy to `Backbone.history` to save a fragment into the history.
965
+ navigate: function(fragment, options) {
966
+ Backbone.history.navigate(fragment, options);
967
+ return this;
968
+ },
969
+
970
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
971
+ // order of the routes here to support behavior where the most general
972
+ // routes can be defined at the bottom of the route map.
973
+ _bindRoutes: function() {
974
+ if (!this.routes) return;
975
+ var route, routes = _.keys(this.routes);
976
+ while ((route = routes.pop()) != null) {
977
+ this.route(route, this.routes[route]);
978
+ }
979
+ },
980
+
981
+ // Convert a route string into a regular expression, suitable for matching
982
+ // against the current location hash.
983
+ _routeToRegExp: function(route) {
984
+ route = route.replace(escapeRegExp, '\\$&')
985
+ .replace(optionalParam, '(?:$1)?')
986
+ .replace(namedParam, function(match, optional){
987
+ return optional ? match : '([^\/]+)';
988
+ })
989
+ .replace(splatParam, '(.*?)');
990
+ return new RegExp('^' + route + '$');
991
+ },
992
+
993
+ // Given a route, and a URL fragment that it matches, return the array of
994
+ // extracted parameters.
995
+ _extractParameters: function(route, fragment) {
996
+ return route.exec(fragment).slice(1);
997
+ }
998
+
999
+ });
1000
+
1001
+ // Backbone.History
1002
+ // ----------------
1003
+
1004
+ // Handles cross-browser history management, based on URL fragments. If the
1005
+ // browser does not support `onhashchange`, falls back to polling.
1006
+ var History = Backbone.History = function() {
1007
+ this.handlers = [];
1008
+ _.bindAll(this, 'checkUrl');
1009
+
1010
+ // Ensure that `History` can be used outside of the browser.
1011
+ if (typeof window !== 'undefined') {
1012
+ this.location = window.location;
1013
+ this.history = window.history;
1014
+ }
1015
+ };
1016
+
1017
+ // Cached regex for stripping a leading hash/slash and trailing space.
1018
+ var routeStripper = /^[#\/]|\s+$/g;
1019
+
1020
+ // Cached regex for stripping leading and trailing slashes.
1021
+ var rootStripper = /^\/+|\/+$/g;
1022
+
1023
+ // Cached regex for detecting MSIE.
1024
+ var isExplorer = /msie [\w.]+/;
1025
+
1026
+ // Cached regex for removing a trailing slash.
1027
+ var trailingSlash = /\/$/;
1028
+
1029
+ // Has the history handling already been started?
1030
+ History.started = false;
1031
+
1032
+ // Set up all inheritable **Backbone.History** properties and methods.
1033
+ _.extend(History.prototype, Events, {
1034
+
1035
+ // The default interval to poll for hash changes, if necessary, is
1036
+ // twenty times a second.
1037
+ interval: 50,
1038
+
1039
+ // Gets the true hash value. Cannot use location.hash directly due to bug
1040
+ // in Firefox where location.hash will always be decoded.
1041
+ getHash: function(window) {
1042
+ var match = (window || this).location.href.match(/#(.*)$/);
1043
+ return match ? match[1] : '';
1044
+ },
1045
+
1046
+ // Get the cross-browser normalized URL fragment, either from the URL,
1047
+ // the hash, or the override.
1048
+ getFragment: function(fragment, forcePushState) {
1049
+ if (fragment == null) {
1050
+ if (this._hasPushState || !this._wantsHashChange || forcePushState) {
1051
+ fragment = this.location.pathname;
1052
+ var root = this.root.replace(trailingSlash, '');
1053
+ if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
1054
+ } else {
1055
+ fragment = this.getHash();
1056
+ }
1057
+ }
1058
+ return fragment.replace(routeStripper, '');
1059
+ },
1060
+
1061
+ // Start the hash change handling, returning `true` if the current URL matches
1062
+ // an existing route, and `false` otherwise.
1063
+ start: function(options) {
1064
+ if (History.started) throw new Error("Backbone.history has already been started");
1065
+ History.started = true;
1066
+
1067
+ // Figure out the initial configuration. Do we need an iframe?
1068
+ // Is pushState desired ... is it available?
1069
+ this.options = _.extend({}, {root: '/'}, this.options, options);
1070
+ this.root = this.options.root;
1071
+ this._wantsHashChange = this.options.hashChange !== false;
1072
+ this._wantsPushState = !!this.options.pushState;
1073
+ this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
1074
+ var fragment = this.getFragment();
1075
+ var docMode = document.documentMode;
1076
+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
1077
+
1078
+ // Normalize root to always include a leading and trailing slash.
1079
+ this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1080
+
1081
+ if (oldIE && this._wantsHashChange) {
1082
+ this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
1083
+ this.navigate(fragment);
1084
+ }
1085
+
1086
+ // Depending on whether we're using pushState or hashes, and whether
1087
+ // 'onhashchange' is supported, determine how we check the URL state.
1088
+ if (this._hasPushState) {
1089
+ Backbone.$(window).on('popstate', this.checkUrl);
1090
+ } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
1091
+ Backbone.$(window).on('hashchange', this.checkUrl);
1092
+ } else if (this._wantsHashChange) {
1093
+ this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1094
+ }
1095
+
1096
+ // Determine if we need to change the base url, for a pushState link
1097
+ // opened by a non-pushState browser.
1098
+ this.fragment = fragment;
1099
+ var loc = this.location;
1100
+ var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
1101
+
1102
+ // If we've started off with a route from a `pushState`-enabled browser,
1103
+ // but we're currently in a browser that doesn't support it...
1104
+ if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
1105
+ this.fragment = this.getFragment(null, true);
1106
+ this.location.replace(this.root + this.location.search + '#' + this.fragment);
1107
+ // Return immediately as browser will do redirect to new url
1108
+ return true;
1109
+
1110
+ // Or if we've started out with a hash-based route, but we're currently
1111
+ // in a browser where it could be `pushState`-based instead...
1112
+ } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
1113
+ this.fragment = this.getHash().replace(routeStripper, '');
1114
+ this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
1115
+ }
1116
+
1117
+ if (!this.options.silent) return this.loadUrl();
1118
+ },
1119
+
1120
+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1121
+ // but possibly useful for unit testing Routers.
1122
+ stop: function() {
1123
+ Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1124
+ clearInterval(this._checkUrlInterval);
1125
+ History.started = false;
1126
+ },
1127
+
1128
+ // Add a route to be tested when the fragment changes. Routes added later
1129
+ // may override previous routes.
1130
+ route: function(route, callback) {
1131
+ this.handlers.unshift({route: route, callback: callback});
1132
+ },
1133
+
1134
+ // Checks the current URL to see if it has changed, and if it has,
1135
+ // calls `loadUrl`, normalizing across the hidden iframe.
1136
+ checkUrl: function(e) {
1137
+ var current = this.getFragment();
1138
+ if (current === this.fragment && this.iframe) {
1139
+ current = this.getFragment(this.getHash(this.iframe));
1140
+ }
1141
+ if (current === this.fragment) return false;
1142
+ if (this.iframe) this.navigate(current);
1143
+ this.loadUrl() || this.loadUrl(this.getHash());
1144
+ },
1145
+
1146
+ // Attempt to load the current URL fragment. If a route succeeds with a
1147
+ // match, returns `true`. If no defined routes matches the fragment,
1148
+ // returns `false`.
1149
+ loadUrl: function(fragmentOverride) {
1150
+ var fragment = this.fragment = this.getFragment(fragmentOverride);
1151
+ var matched = _.any(this.handlers, function(handler) {
1152
+ if (handler.route.test(fragment)) {
1153
+ handler.callback(fragment);
1154
+ return true;
1155
+ }
1156
+ });
1157
+ return matched;
1158
+ },
1159
+
1160
+ // Save a fragment into the hash history, or replace the URL state if the
1161
+ // 'replace' option is passed. You are responsible for properly URL-encoding
1162
+ // the fragment in advance.
1163
+ //
1164
+ // The options object can contain `trigger: true` if you wish to have the
1165
+ // route callback be fired (not usually desirable), or `replace: true`, if
1166
+ // you wish to modify the current URL without adding an entry to the history.
1167
+ navigate: function(fragment, options) {
1168
+ if (!History.started) return false;
1169
+ if (!options || options === true) options = {trigger: options};
1170
+ fragment = this.getFragment(fragment || '');
1171
+ if (this.fragment === fragment) return;
1172
+ this.fragment = fragment;
1173
+ var url = this.root + fragment;
1174
+
1175
+ // If pushState is available, we use it to set the fragment as a real URL.
1176
+ if (this._hasPushState) {
1177
+ this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1178
+
1179
+ // If hash changes haven't been explicitly disabled, update the hash
1180
+ // fragment to store history.
1181
+ } else if (this._wantsHashChange) {
1182
+ this._updateHash(this.location, fragment, options.replace);
1183
+ if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
1184
+ // Opening and closing the iframe tricks IE7 and earlier to push a
1185
+ // history entry on hash-tag change. When replace is true, we don't
1186
+ // want this.
1187
+ if(!options.replace) this.iframe.document.open().close();
1188
+ this._updateHash(this.iframe.location, fragment, options.replace);
1189
+ }
1190
+
1191
+ // If you've told us that you explicitly don't want fallback hashchange-
1192
+ // based history, then `navigate` becomes a page refresh.
1193
+ } else {
1194
+ return this.location.assign(url);
1195
+ }
1196
+ if (options.trigger) this.loadUrl(fragment);
1197
+ },
1198
+
1199
+ // Update the hash location, either replacing the current entry, or adding
1200
+ // a new one to the browser history.
1201
+ _updateHash: function(location, fragment, replace) {
1202
+ if (replace) {
1203
+ var href = location.href.replace(/(javascript:|#).*$/, '');
1204
+ location.replace(href + '#' + fragment);
1205
+ } else {
1206
+ // Some browsers require that `hash` contains a leading #.
1207
+ location.hash = '#' + fragment;
1208
+ }
1209
+ }
1210
+
1211
+ });
1212
+
1213
+ // Create the default Backbone.history.
1214
+ Backbone.history = new History;
1215
+
1216
+ // Backbone.View
1217
+ // -------------
1218
+
1219
+ // Creating a Backbone.View creates its initial element outside of the DOM,
1220
+ // if an existing element is not provided...
1221
+ var View = Backbone.View = function(options) {
1222
+ this.cid = _.uniqueId('view');
1223
+ this._configure(options || {});
1224
+ this._ensureElement();
1225
+ this.initialize.apply(this, arguments);
1226
+ this.delegateEvents();
1227
+ };
1228
+
1229
+ // Cached regex to split keys for `delegate`.
1230
+ var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1231
+
1232
+ // List of view options to be merged as properties.
1233
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1234
+
1235
+ // Set up all inheritable **Backbone.View** properties and methods.
1236
+ _.extend(View.prototype, Events, {
1237
+
1238
+ // The default `tagName` of a View's element is `"div"`.
1239
+ tagName: 'div',
1240
+
1241
+ // jQuery delegate for element lookup, scoped to DOM elements within the
1242
+ // current view. This should be prefered to global lookups where possible.
1243
+ $: function(selector) {
1244
+ return this.$el.find(selector);
1245
+ },
1246
+
1247
+ // Initialize is an empty function by default. Override it with your own
1248
+ // initialization logic.
1249
+ initialize: function(){},
1250
+
1251
+ // **render** is the core function that your view should override, in order
1252
+ // to populate its element (`this.el`), with the appropriate HTML. The
1253
+ // convention is for **render** to always return `this`.
1254
+ render: function() {
1255
+ return this;
1256
+ },
1257
+
1258
+ // Remove this view by taking the element out of the DOM, and removing any
1259
+ // applicable Backbone.Events listeners.
1260
+ remove: function() {
1261
+ this.$el.remove();
1262
+ this.stopListening();
1263
+ return this;
1264
+ },
1265
+
1266
+ // Change the view's element (`this.el` property), including event
1267
+ // re-delegation.
1268
+ setElement: function(element, delegate) {
1269
+ if (this.$el) this.undelegateEvents();
1270
+ this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
1271
+ this.el = this.$el[0];
1272
+ if (delegate !== false) this.delegateEvents();
1273
+ return this;
1274
+ },
1275
+
1276
+ // Set callbacks, where `this.events` is a hash of
1277
+ //
1278
+ // *{"event selector": "callback"}*
1279
+ //
1280
+ // {
1281
+ // 'mousedown .title': 'edit',
1282
+ // 'click .button': 'save'
1283
+ // 'click .open': function(e) { ... }
1284
+ // }
1285
+ //
1286
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
1287
+ // Uses event delegation for efficiency.
1288
+ // Omitting the selector binds the event to `this.el`.
1289
+ // This only works for delegate-able events: not `focus`, `blur`, and
1290
+ // not `change`, `submit`, and `reset` in Internet Explorer.
1291
+ delegateEvents: function(events) {
1292
+ if (!(events || (events = _.result(this, 'events')))) return;
1293
+ this.undelegateEvents();
1294
+ for (var key in events) {
1295
+ var method = events[key];
1296
+ if (!_.isFunction(method)) method = this[events[key]];
1297
+ if (!method) throw new Error('Method "' + events[key] + '" does not exist');
1298
+ var match = key.match(delegateEventSplitter);
1299
+ var eventName = match[1], selector = match[2];
1300
+ method = _.bind(method, this);
1301
+ eventName += '.delegateEvents' + this.cid;
1302
+ if (selector === '') {
1303
+ this.$el.on(eventName, method);
1304
+ } else {
1305
+ this.$el.on(eventName, selector, method);
1306
+ }
1307
+ }
1308
+ },
1309
+
1310
+ // Clears all callbacks previously bound to the view with `delegateEvents`.
1311
+ // You usually don't need to use this, but may wish to if you have multiple
1312
+ // Backbone views attached to the same DOM element.
1313
+ undelegateEvents: function() {
1314
+ this.$el.off('.delegateEvents' + this.cid);
1315
+ },
1316
+
1317
+ // Performs the initial configuration of a View with a set of options.
1318
+ // Keys with special meaning *(model, collection, id, className)*, are
1319
+ // attached directly to the view.
1320
+ _configure: function(options) {
1321
+ if (this.options) options = _.extend({}, _.result(this, 'options'), options);
1322
+ _.extend(this, _.pick(options, viewOptions));
1323
+ this.options = options;
1324
+ },
1325
+
1326
+ // Ensure that the View has a DOM element to render into.
1327
+ // If `this.el` is a string, pass it through `$()`, take the first
1328
+ // matching element, and re-assign it to `el`. Otherwise, create
1329
+ // an element from the `id`, `className` and `tagName` properties.
1330
+ _ensureElement: function() {
1331
+ if (!this.el) {
1332
+ var attrs = _.extend({}, _.result(this, 'attributes'));
1333
+ if (this.id) attrs.id = _.result(this, 'id');
1334
+ if (this.className) attrs['class'] = _.result(this, 'className');
1335
+ var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
1336
+ this.setElement($el, false);
1337
+ } else {
1338
+ this.setElement(_.result(this, 'el'), false);
1339
+ }
1340
+ }
1341
+
1342
+ });
1343
+
1344
+ // Backbone.sync
1345
+ // -------------
1346
+
1347
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1348
+ var methodMap = {
1349
+ 'create': 'POST',
1350
+ 'update': 'PUT',
1351
+ 'patch': 'PATCH',
1352
+ 'delete': 'DELETE',
1353
+ 'read': 'GET'
1354
+ };
1355
+
1356
+ // Override this function to change the manner in which Backbone persists
1357
+ // models to the server. You will be passed the type of request, and the
1358
+ // model in question. By default, makes a RESTful Ajax request
1359
+ // to the model's `url()`. Some possible customizations could be:
1360
+ //
1361
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
1362
+ // * Send up the models as XML instead of JSON.
1363
+ // * Persist models via WebSockets instead of Ajax.
1364
+ //
1365
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1366
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
1367
+ // as well as all requests with the body as `application/x-www-form-urlencoded`
1368
+ // instead of `application/json` with the model in a param named `model`.
1369
+ // Useful when interfacing with server-side languages like **PHP** that make
1370
+ // it difficult to read the body of `PUT` requests.
1371
+ Backbone.sync = function(method, model, options) {
1372
+ var type = methodMap[method];
1373
+
1374
+ // Default options, unless specified.
1375
+ _.defaults(options || (options = {}), {
1376
+ emulateHTTP: Backbone.emulateHTTP,
1377
+ emulateJSON: Backbone.emulateJSON
1378
+ });
1379
+
1380
+ // Default JSON-request options.
1381
+ var params = {type: type, dataType: 'json'};
1382
+
1383
+ // Ensure that we have a URL.
1384
+ if (!options.url) {
1385
+ params.url = _.result(model, 'url') || urlError();
1386
+ }
1387
+
1388
+ // Ensure that we have the appropriate request data.
1389
+ if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1390
+ params.contentType = 'application/json';
1391
+ params.data = JSON.stringify(options.attrs || model.toJSON(options));
1392
+ }
1393
+
1394
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
1395
+ if (options.emulateJSON) {
1396
+ params.contentType = 'application/x-www-form-urlencoded';
1397
+ params.data = params.data ? {model: params.data} : {};
1398
+ }
1399
+
1400
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1401
+ // And an `X-HTTP-Method-Override` header.
1402
+ if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1403
+ params.type = 'POST';
1404
+ if (options.emulateJSON) params.data._method = type;
1405
+ var beforeSend = options.beforeSend;
1406
+ options.beforeSend = function(xhr) {
1407
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
1408
+ if (beforeSend) return beforeSend.apply(this, arguments);
1409
+ };
1410
+ }
1411
+
1412
+ // Don't process data on a non-GET request.
1413
+ if (params.type !== 'GET' && !options.emulateJSON) {
1414
+ params.processData = false;
1415
+ }
1416
+
1417
+ var success = options.success;
1418
+ options.success = function(resp) {
1419
+ if (success) success(model, resp, options);
1420
+ model.trigger('sync', model, resp, options);
1421
+ };
1422
+
1423
+ var error = options.error;
1424
+ options.error = function(xhr) {
1425
+ if (error) error(model, xhr, options);
1426
+ model.trigger('error', model, xhr, options);
1427
+ };
1428
+
1429
+ // Make the request, allowing the user to override any Ajax options.
1430
+ var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1431
+ model.trigger('request', model, xhr, options);
1432
+ return xhr;
1433
+ };
1434
+
1435
+ // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1436
+ Backbone.ajax = function() {
1437
+ return Backbone.$.ajax.apply(Backbone.$, arguments);
1438
+ };
1439
+
1440
+ // Helpers
1441
+ // -------
1442
+
1443
+ // Helper function to correctly set up the prototype chain, for subclasses.
1444
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
1445
+ // class properties to be extended.
1446
+ var extend = function(protoProps, staticProps) {
1447
+ var parent = this;
1448
+ var child;
1449
+
1450
+ // The constructor function for the new subclass is either defined by you
1451
+ // (the "constructor" property in your `extend` definition), or defaulted
1452
+ // by us to simply call the parent's constructor.
1453
+ if (protoProps && _.has(protoProps, 'constructor')) {
1454
+ child = protoProps.constructor;
1455
+ } else {
1456
+ child = function(){ return parent.apply(this, arguments); };
1457
+ }
1458
+
1459
+ // Add static properties to the constructor function, if supplied.
1460
+ _.extend(child, parent, staticProps);
1461
+
1462
+ // Set the prototype chain to inherit from `parent`, without calling
1463
+ // `parent`'s constructor function.
1464
+ var Surrogate = function(){ this.constructor = child; };
1465
+ Surrogate.prototype = parent.prototype;
1466
+ child.prototype = new Surrogate;
1467
+
1468
+ // Add prototype properties (instance properties) to the subclass,
1469
+ // if supplied.
1470
+ if (protoProps) _.extend(child.prototype, protoProps);
1471
+
1472
+ // Set a convenience property in case the parent's prototype is needed
1473
+ // later.
1474
+ child.__super__ = parent.prototype;
1475
+
1476
+ return child;
1477
+ };
1478
+
1479
+ // Set up inheritance for the model, collection, router, view and history.
1480
+ Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1481
+
1482
+ // Throw an error when a URL is needed, and none is supplied.
1483
+ var urlError = function() {
1484
+ throw new Error('A "url" property or function must be specified');
1485
+ };
1486
+
1487
+ }).call(this);