ultimate-base 0.2.0

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