Debian Codegraph @

test/vendor/backbone.js

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