atlas_assets 0.0.7

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