auto_error 0.0.2 → 0.0.3

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