3 // (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
4 // Backbone may be freely distributed under the MIT license.
5 // For all details and documentation:
6 // http://backbonejs.org
8 (function(root, factory) {
10 // Set up Backbone appropriately for the environment. Start with AMD.
11 if (typeof define === 'function' && define.amd) {
12 define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
13 // Export global even in AMD case in case this script is loaded with
14 // others that may still expect a global Backbone.
15 root.Backbone = factory(root, exports, _, $);
18 // Next for Node.js or CommonJS. jQuery may not be needed as a module.
19 } else if (typeof exports !== 'undefined') {
20 var _ = require('underscore');
21 factory(root, exports, _);
23 // Finally, as a browser global.
25 root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
28 }(this, function(root, Backbone, _, $) {
33 // Save the previous value of the `Backbone` variable, so that it can be
34 // restored later on, if `noConflict` is used.
35 var previousBackbone = root.Backbone;
37 // Create local references to array methods we'll want to use later.
39 var slice = array.slice;
41 // Current version of the library. Keep in sync with `package.json`.
42 Backbone.VERSION = '1.1.2';
44 // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
48 // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
49 // to its previous owner. Returns a reference to this Backbone object.
50 Backbone.noConflict = function() {
51 root.Backbone = previousBackbone;
55 // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
56 // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
57 // set a `X-Http-Method-Override` header.
58 Backbone.emulateHTTP = false;
60 // Turn on `emulateJSON` to support legacy servers that can't deal with direct
61 // `application/json` requests ... this will encode the body as
62 // `application/x-www-form-urlencoded` instead and will send the model in a
63 // form param named `model`.
64 Backbone.emulateJSON = false;
69 // A module that can be mixed in to *any object* in order to provide it with
70 // custom events. You may bind with `on` or remove with `off` callback
71 // functions to an event; `trigger`-ing an event fires all callbacks in
75 // _.extend(object, Backbone.Events);
76 // object.on('expand', function(){ alert('expanded'); });
77 // object.trigger('expand');
79 var Events = Backbone.Events = {};
81 // Regular expression used to split event strings.
82 var eventSplitter = /\s+/;
84 // Iterates over the standard `event, callback` (as well as the fancy multiple
85 // space-separated events `"change blur", callback` and jQuery-style event
86 // maps `{event: callback}`), reducing them by manipulating `events`.
87 // Passes a normalized (single event name and callback), as well as the `context`
88 // and `ctx` arguments to `iteratee`.
89 var eventsApi = function(iteratee, memo, name, callback, context, ctx) {
90 var i = 0, names, length;
91 if (name && typeof name === 'object') {
93 for (names = _.keys(name); i < names.length; i++) {
94 memo = iteratee(memo, names[i], name[names[i]], context, ctx);
96 } else if (name && eventSplitter.test(name)) {
97 // Handle space separated event names.
98 for (names = name.split(eventSplitter); i < names.length; i++) {
99 memo = iteratee(memo, names[i], callback, context, ctx);
102 memo = iteratee(memo, name, callback, context, ctx);
107 // Bind an event to a `callback` function. Passing `"all"` will bind
108 // the callback to all events fired.
109 Events.on = function(name, callback, context) {
110 this._events = eventsApi(onApi, this._events || {}, name, callback, context, this);
114 // Inversion-of-control versions of `on`. Tell *this* object to listen to
115 // an event in another object... keeping track of what it's listening to.
116 Events.listenTo = function(obj, name, callback) {
117 if (!obj) return this;
118 var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
119 var listeningTo = this._listeningTo || (this._listeningTo = {});
120 var listening = listeningTo[id];
122 // This object is not listening to any other events on `obj` yet.
123 // Setup the necessary references to track the listening callbacks.
125 listening = listeningTo[id] = {obj: obj, events: {}};
126 id = this._listenId || (this._listenId = _.uniqueId('l'));
127 var listeners = obj._listeners || (obj._listeners = {});
128 listeners[id] = this;
131 // Bind callbacks on obj, and keep track of them on listening.
132 obj.on(name, callback, this);
133 listening.events = eventsApi(onApi, listening.events, name, callback);
137 // The reducing API that adds a callback to the `events` object.
138 var onApi = function(events, name, callback, context, ctx) {
140 var handlers = events[name] || (events[name] = []);
141 handlers.push({callback: callback, context: context, ctx: context || ctx});
146 // Remove one or many callbacks. If `context` is null, removes all
147 // callbacks with that function. If `callback` is null, removes all
148 // callbacks for the event. If `name` is null, removes all bound
149 // callbacks for all events.
150 Events.off = function(name, callback, context) {
151 if (!this._events) return this;
152 this._events = eventsApi(offApi, this._events, name, callback, context);
154 var listeners = this._listeners;
156 // Listeners always bind themselves as the context, so if `context`
157 // is passed, narrow down the search to just that listener.
158 var ids = context != null ? [context._listenId] : _.keys(listeners);
160 for (var i = 0; i < ids.length; i++) {
161 var listener = listeners[ids[i]];
163 // Bail out if listener isn't listening.
164 if (!listener) break;
166 // Tell each listener to stop, without infinitely calling `#off`.
167 internalStopListening(listener, this, name, callback);
169 if (_.isEmpty(listeners)) this._listeners = void 0;
174 // Tell this object to stop listening to either specific events ... or
175 // to every object it's currently listening to.
176 Events.stopListening = function(obj, name, callback) {
177 // Use an internal stopListening, telling it to call off on `obj`.
178 if (this._listeningTo) internalStopListening(this, obj, name, callback, true);
182 // The reducing API that removes a callback from the `events` object.
183 var offApi = function(events, name, callback, context) {
184 // Remove all callbacks for all events.
185 if (!events || !name && !context && !callback) return;
187 var names = name ? [name] : _.keys(events);
188 for (var i = 0; i < names.length; i++) {
190 var handlers = events[name];
192 // Bail out if there are no events stored.
193 if (!handlers) break;
195 // Find any remaining events.
197 if (callback || context) {
198 for (var j = 0, k = handlers.length; j < k; j++) {
199 var handler = handlers[j];
201 callback && callback !== handler.callback &&
202 callback !== handler.callback._callback ||
203 context && context !== handler.context
205 remaining.push(handler);
210 // Replace events if there are any remaining. Otherwise, clean up.
211 if (remaining.length) {
212 events[name] = remaining;
217 if (!_.isEmpty(events)) return events;
220 var internalStopListening = function(listener, obj, name, callback, offEvents) {
221 var listeningTo = listener._listeningTo;
222 var ids = obj ? [obj._listenId] : _.keys(listeningTo);
223 for (var i = 0; i < ids.length; i++) {
225 var listening = listeningTo[id];
227 // If listening doesn't exist, this object is not currently
228 // listening to obj. Break out early.
229 if (!listening) break;
231 if (offEvents) obj._events = eventsApi(offApi, obj._events, name, callback, listener);
233 // Events will only ever be falsey if all the event callbacks
234 // are removed. If so, stop delete the listening.
235 var events = eventsApi(offApi, listening.events, name, callback);
237 delete listeningTo[id];
238 delete listening.obj._listeners[listener._listenId];
241 if (_.isEmpty(listeningTo)) listener._listeningTo = void 0;
244 // Bind an event to only be triggered a single time. After the first time
245 // the callback is invoked, it will be removed.
246 Events.once = function(name, callback, context) {
247 // Map the event into a `{event: once}` object.
248 var events = onceMap(name, callback, _.bind(this.off, this));
249 return this.on(events, void 0, context);
252 // Inversion-of-control versions of `once`.
253 Events.listenToOnce = function(obj, name, callback) {
254 // Map the event into a `{event: once}` object.
255 var events = onceMap(name, callback, _.bind(this.stopListening, this, obj));
256 return this.listenTo(obj, events);
259 // Reduces the event callbacks into a map of `{event: onceWrapper}`.
260 // `offer` unbinds the `onceWrapper` after it as been called.
261 var onceMap = function(name, callback, offer) {
262 return eventsApi(function(map, name, callback, offer) {
264 var once = map[name] = _.once(function() {
266 callback.apply(this, arguments);
268 once._callback = callback;
271 }, {}, name, callback, offer);
274 // Trigger one or many events, firing all bound callbacks. Callbacks are
275 // passed the same arguments as `trigger` is, apart from the event name
276 // (unless you're listening on `"all"`, which will cause your callback to
277 // receive the true name of the event as the first argument).
278 Events.trigger = function(name) {
279 if (!this._events) return this;
281 var length = Math.max(0, arguments.length - 1);
282 var args = Array(length);
283 for (var i = 0; i < length; i++) args[i] = arguments[i + 1];
285 eventsApi(triggerApi, this, name, void 0, args);
289 // Handles triggering the appropriate event callbacks.
290 var triggerApi = function(obj, name, cb, args) {
292 var events = obj._events[name];
293 var allEvents = obj._events.all;
294 if (events) triggerEvents(events, args);
295 if (allEvents) triggerEvents(allEvents, [name].concat(args));
300 // A difficult-to-believe, but optimized internal dispatch function for
301 // triggering events. Tries to keep the usual cases speedy (most internal
302 // Backbone events have 3 arguments).
303 var triggerEvents = function(events, args) {
304 var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
305 switch (args.length) {
306 case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
307 case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
308 case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
309 case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
310 default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
314 // Proxy Underscore methods to a Backbone class' prototype using a
315 // particular attribute as the data argument
316 var addMethod = function(length, method, attribute) {
318 case 1: return function() {
319 return _[method](this[attribute]);
321 case 2: return function(value) {
322 return _[method](this[attribute], value);
324 case 3: return function(iteratee, context) {
325 return _[method](this[attribute], iteratee, context);
327 case 4: return function(iteratee, defaultVal, context) {
328 return _[method](this[attribute], iteratee, defaultVal, context);
330 default: return function() {
331 var args = slice.call(arguments);
332 args.unshift(this[attribute]);
333 return _[method].apply(_, args);
337 var addUnderscoreMethods = function(Class, methods, attribute) {
338 _.each(methods, function(length, method) {
339 if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
343 // Aliases for backwards compatibility.
344 Events.bind = Events.on;
345 Events.unbind = Events.off;
347 // Allow the `Backbone` object to serve as a global event bus, for folks who
348 // want global "pubsub" in a convenient place.
349 _.extend(Backbone, Events);
354 // Backbone **Models** are the basic data object in the framework --
355 // frequently representing a row in a table in a database on your server.
356 // A discrete chunk of data and a bunch of useful, related methods for
357 // performing computations and transformations on that data.
359 // Create a new model with the specified attributes. A client id (`cid`)
360 // is automatically generated and assigned for you.
361 var Model = Backbone.Model = function(attributes, options) {
362 var attrs = attributes || {};
363 options || (options = {});
364 this.cid = _.uniqueId(this.cidPrefix);
365 this.attributes = {};
366 if (options.collection) this.collection = options.collection;
367 if (options.parse) attrs = this.parse(attrs, options) || {};
368 attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
369 this.set(attrs, options);
371 this.initialize.apply(this, arguments);
374 // Attach all inheritable methods to the Model prototype.
375 _.extend(Model.prototype, Events, {
377 // A hash of attributes whose current and previous value differ.
380 // The value returned during the last failed validation.
381 validationError: null,
383 // The default name for the JSON `id` attribute is `"id"`. MongoDB and
384 // CouchDB users may want to set this to `"_id"`.
387 // The prefix is used to create the client id which is used to identify models locally.
388 // You may want to override this if you're experiencing name clashes with model ids.
391 // Initialize is an empty function by default. Override it with your own
392 // initialization logic.
393 initialize: function(){},
395 // Return a copy of the model's `attributes` object.
396 toJSON: function(options) {
397 return _.clone(this.attributes);
400 // Proxy `Backbone.sync` by default -- but override this if you need
401 // custom syncing semantics for *this* particular model.
403 return Backbone.sync.apply(this, arguments);
406 // Get the value of an attribute.
407 get: function(attr) {
408 return this.attributes[attr];
411 // Get the HTML-escaped value of an attribute.
412 escape: function(attr) {
413 return _.escape(this.get(attr));
416 // Returns `true` if the attribute contains a value that is not null
418 has: function(attr) {
419 return this.get(attr) != null;
422 // Special-cased proxy to underscore's `_.matches` method.
423 matches: function(attrs) {
424 return _.matches(attrs)(this.attributes);
427 // Set a hash of model attributes on the object, firing `"change"`. This is
428 // the core primitive operation of a model, updating the data and notifying
429 // anyone who needs to know about the change in state. The heart of the beast.
430 set: function(key, val, options) {
431 var attr, attrs, unset, changes, silent, changing, prev, current;
432 if (key == null) return this;
434 // Handle both `"key", value` and `{key: value}` -style arguments.
435 if (typeof key === 'object') {
439 (attrs = {})[key] = val;
442 options || (options = {});
445 if (!this._validate(attrs, options)) return false;
447 // Extract attributes and options.
448 unset = options.unset;
449 silent = options.silent;
451 changing = this._changing;
452 this._changing = true;
455 this._previousAttributes = _.clone(this.attributes);
458 current = this.attributes, prev = this._previousAttributes;
460 // Check for changes of `id`.
461 if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
463 // For each `set` attribute, update or delete the current value.
464 for (attr in attrs) {
466 if (!_.isEqual(current[attr], val)) changes.push(attr);
467 if (!_.isEqual(prev[attr], val)) {
468 this.changed[attr] = val;
470 delete this.changed[attr];
472 unset ? delete current[attr] : current[attr] = val;
475 // Trigger all relevant attribute changes.
477 if (changes.length) this._pending = options;
478 for (var i = 0; i < changes.length; i++) {
479 this.trigger('change:' + changes[i], this, current[changes[i]], options);
483 // You might be wondering why there's a `while` loop here. Changes can
484 // be recursively nested within `"change"` events.
485 if (changing) return this;
487 while (this._pending) {
488 options = this._pending;
489 this._pending = false;
490 this.trigger('change', this, options);
493 this._pending = false;
494 this._changing = false;
498 // Remove an attribute from the model, firing `"change"`. `unset` is a noop
499 // if the attribute doesn't exist.
500 unset: function(attr, options) {
501 return this.set(attr, void 0, _.extend({}, options, {unset: true}));
504 // Clear all attributes on the model, firing `"change"`.
505 clear: function(options) {
507 for (var key in this.attributes) attrs[key] = void 0;
508 return this.set(attrs, _.extend({}, options, {unset: true}));
511 // Determine if the model has changed since the last `"change"` event.
512 // If you specify an attribute name, determine if that attribute has changed.
513 hasChanged: function(attr) {
514 if (attr == null) return !_.isEmpty(this.changed);
515 return _.has(this.changed, attr);
518 // Return an object containing all the attributes that have changed, or
519 // false if there are no changed attributes. Useful for determining what
520 // parts of a view need to be updated and/or what attributes need to be
521 // persisted to the server. Unset attributes will be set to undefined.
522 // You can also pass an attributes object to diff against the model,
523 // determining if there *would be* a change.
524 changedAttributes: function(diff) {
525 if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
526 var val, changed = false;
527 var old = this._changing ? this._previousAttributes : this.attributes;
528 for (var attr in diff) {
529 if (_.isEqual(old[attr], (val = diff[attr]))) continue;
530 (changed || (changed = {}))[attr] = val;
535 // Get the previous value of an attribute, recorded at the time the last
536 // `"change"` event was fired.
537 previous: function(attr) {
538 if (attr == null || !this._previousAttributes) return null;
539 return this._previousAttributes[attr];
542 // Get all of the attributes of the model at the time of the previous
544 previousAttributes: function() {
545 return _.clone(this._previousAttributes);
548 // Fetch the model from the server, merging the response with the model's
549 // local attributes. Any changed attributes will trigger a "change" event.
550 fetch: function(options) {
551 options = options ? _.clone(options) : {};
552 if (options.parse === void 0) options.parse = true;
554 var success = options.success;
555 options.success = function(resp) {
556 if (!model.set(model.parse(resp, options), options)) return false;
557 if (success) success.call(options.context, model, resp, options);
558 model.trigger('sync', model, resp, options);
560 wrapError(this, options);
561 return this.sync('read', this, options);
564 // Set a hash of model attributes, and sync the model to the server.
565 // If the server returns an attributes hash that differs, the model's
566 // state will be `set` again.
567 save: function(key, val, options) {
568 var attrs, method, xhr, attributes = this.attributes, wait;
570 // Handle both `"key", value` and `{key: value}` -style arguments.
571 if (key == null || typeof key === 'object') {
575 (attrs = {})[key] = val;
578 options = _.extend({validate: true}, options);
581 // If we're not waiting and attributes exist, save acts as
582 // `set(attr).save(null, opts)` with validation. Otherwise, check if
583 // the model will be valid when the attributes, if any, are set.
584 if (attrs && !wait) {
585 if (!this.set(attrs, options)) return false;
587 if (!this._validate(attrs, options)) return false;
590 // Set temporary attributes if `{wait: true}`.
592 this.attributes = _.extend({}, attributes, attrs);
595 // After a successful server-side save, the client is (optionally)
596 // updated with the server-side state.
597 if (options.parse === void 0) options.parse = true;
599 var success = options.success;
600 options.success = function(resp) {
601 // Ensure attributes are restored during synchronous saves.
602 model.attributes = attributes;
603 var serverAttrs = options.parse ? model.parse(resp, options) : resp;
604 if (wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
605 if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
608 if (success) success.call(options.context, model, resp, options);
609 model.trigger('sync', model, resp, options);
611 wrapError(this, options);
613 method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
614 if (method === 'patch' && !options.attrs) options.attrs = attrs;
615 xhr = this.sync(method, this, options);
617 // Restore attributes.
618 if (attrs && wait) this.attributes = attributes;
623 // Destroy this model on the server if it was already persisted.
624 // Optimistically removes the model from its collection, if it has one.
625 // If `wait: true` is passed, waits for the server to respond before removal.
626 destroy: function(options) {
627 options = options ? _.clone(options) : {};
629 var success = options.success;
630 var wait = options.wait;
632 var destroy = function() {
633 model.stopListening();
634 model.trigger('destroy', model, model.collection, options);
637 options.success = function(resp) {
638 if (wait || model.isNew()) destroy();
639 if (success) success.call(options.context, model, resp, options);
640 if (!model.isNew()) model.trigger('sync', model, resp, options);
647 wrapError(this, options);
649 var xhr = this.sync('delete', this, options);
650 if (!wait) destroy();
654 // Default URL for the model's representation on the server -- if you're
655 // using Backbone's restful methods, override this to change the endpoint
656 // that will be called.
659 _.result(this, 'urlRoot') ||
660 _.result(this.collection, 'url') ||
662 if (this.isNew()) return base;
663 var id = this.id || this.attributes[this.idAttribute];
664 return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(id);
667 // **parse** converts a response into the hash of attributes to be `set` on
668 // the model. The default implementation is just to pass the response along.
669 parse: function(resp, options) {
673 // Create a new model with identical attributes to this one.
675 return new this.constructor(this.attributes);
678 // A model is new if it has never been saved to the server, and lacks an id.
680 return !this.has(this.idAttribute);
683 // Check if the model is currently in a valid state.
684 isValid: function(options) {
685 return this._validate({}, _.extend(options || {}, { validate: true }));
688 // Run validation against the next complete set of model attributes,
689 // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
690 _validate: function(attrs, options) {
691 if (!options.validate || !this.validate) return true;
692 attrs = _.extend({}, this.attributes, attrs);
693 var error = this.validationError = this.validate(attrs, options) || null;
694 if (!error) return true;
695 this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
701 // Underscore methods that we want to implement on the Model.
702 var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
703 omit: 0, chain: 1, isEmpty: 1 };
705 // Mix in each Underscore method as a proxy to `Model#attributes`.
706 addUnderscoreMethods(Model, modelMethods, 'attributes');
708 // Backbone.Collection
709 // -------------------
711 // If models tend to represent a single row of data, a Backbone Collection is
712 // more analogous to a table full of data ... or a small slice or page of that
713 // table, or a collection of rows that belong together for a particular reason
714 // -- all of the messages in this particular folder, all of the documents
715 // belonging to this particular author, and so on. Collections maintain
716 // indexes of their models, both in order, and for lookup by `id`.
718 // Create a new **Collection**, perhaps to contain a specific type of `model`.
719 // If a `comparator` is specified, the Collection will maintain
720 // its models in sort order, as they're added and removed.
721 var Collection = Backbone.Collection = function(models, options) {
722 options || (options = {});
723 if (options.model) this.model = options.model;
724 if (options.comparator !== void 0) this.comparator = options.comparator;
726 this.initialize.apply(this, arguments);
727 if (models) this.reset(models, _.extend({silent: true}, options));
730 // Default options for `Collection#set`.
731 var setOptions = {add: true, remove: true, merge: true};
732 var addOptions = {add: true, remove: false};
734 // Define the Collection's inheritable methods.
735 _.extend(Collection.prototype, Events, {
737 // The default model for a collection is just a **Backbone.Model**.
738 // This should be overridden in most cases.
741 // Initialize is an empty function by default. Override it with your own
742 // initialization logic.
743 initialize: function(){},
745 // The JSON representation of a Collection is an array of the
746 // models' attributes.
747 toJSON: function(options) {
748 return this.map(function(model){ return model.toJSON(options); });
751 // Proxy `Backbone.sync` by default.
753 return Backbone.sync.apply(this, arguments);
756 // Add a model, or list of models to the set.
757 add: function(models, options) {
758 return this.set(models, _.extend({merge: false}, options, addOptions));
761 // Remove a model, or a list of models from the set.
762 remove: function(models, options) {
763 var singular = !_.isArray(models);
764 models = singular ? [models] : _.clone(models);
765 options || (options = {});
766 for (var i = 0; i < models.length; i++) {
767 var model = models[i] = this.get(models[i]);
768 if (!model) continue;
769 var id = this.modelId(model.attributes);
770 if (id != null) delete this._byId[id];
771 delete this._byId[model.cid];
772 var index = this.indexOf(model);
773 this.models.splice(index, 1);
775 if (!options.silent) {
776 options.index = index;
777 model.trigger('remove', model, this, options);
779 this._removeReference(model, options);
781 return singular ? models[0] : models;
784 // Update a collection by `set`-ing a new list of models, adding new ones,
785 // removing models that are no longer present, and merging models that
786 // already exist in the collection, as necessary. Similar to **Model#set**,
787 // the core operation for updating the data contained by the collection.
788 set: function(models, options) {
789 options = _.defaults({}, options, setOptions);
790 if (options.parse) models = this.parse(models, options);
791 var singular = !_.isArray(models);
792 models = singular ? (models ? [models] : []) : models.slice();
793 var id, model, attrs, existing, sort;
795 if (at != null) at = +at;
796 if (at < 0) at += this.length + 1;
797 var sortable = this.comparator && (at == null) && options.sort !== false;
798 var sortAttr = _.isString(this.comparator) ? this.comparator : null;
799 var toAdd = [], toRemove = [], modelMap = {};
800 var add = options.add, merge = options.merge, remove = options.remove;
801 var order = !sortable && add && remove ? [] : false;
802 var orderChanged = false;
804 // Turn bare objects into model references, and prevent invalid models
806 for (var i = 0; i < models.length; i++) {
809 // If a duplicate is found, prevent it from being added and
810 // optionally merge it into the existing model.
811 if (existing = this.get(attrs)) {
812 if (remove) modelMap[existing.cid] = true;
813 if (merge && attrs !== existing) {
814 attrs = this._isModel(attrs) ? attrs.attributes : attrs;
815 if (options.parse) attrs = existing.parse(attrs, options);
816 existing.set(attrs, options);
817 if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
819 models[i] = existing;
821 // If this is a new, valid model, push it to the `toAdd` list.
823 model = models[i] = this._prepareModel(attrs, options);
824 if (!model) continue;
826 this._addReference(model, options);
829 // Do not add multiple models with the same `id`.
830 model = existing || model;
831 if (!model) continue;
832 id = this.modelId(model.attributes);
833 if (order && (model.isNew() || !modelMap[id])) {
836 // Check to see if this is actually a new model at this index.
837 orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid;
843 // Remove nonexistent models if appropriate.
845 for (var i = 0; i < this.length; i++) {
846 if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
848 if (toRemove.length) this.remove(toRemove, options);
851 // See if sorting is needed, update `length` and splice in new models.
852 if (toAdd.length || orderChanged) {
853 if (sortable) sort = true;
854 this.length += toAdd.length;
856 for (var i = 0; i < toAdd.length; i++) {
857 this.models.splice(at + i, 0, toAdd[i]);
860 if (order) this.models.length = 0;
861 var orderedModels = order || toAdd;
862 for (var i = 0; i < orderedModels.length; i++) {
863 this.models.push(orderedModels[i]);
868 // Silently sort the collection if appropriate.
869 if (sort) this.sort({silent: true});
871 // Unless silenced, it's time to fire all appropriate add/sort events.
872 if (!options.silent) {
873 var addOpts = at != null ? _.clone(options) : options;
874 for (var i = 0; i < toAdd.length; i++) {
875 if (at != null) addOpts.index = at + i;
876 (model = toAdd[i]).trigger('add', model, this, addOpts);
878 if (sort || orderChanged) this.trigger('sort', this, options);
881 // Return the added (or merged) model (or models).
882 return singular ? models[0] : models;
885 // When you have more items than you want to add or remove individually,
886 // you can reset the entire set with a new list of models, without firing
887 // any granular `add` or `remove` events. Fires `reset` when finished.
888 // Useful for bulk operations and optimizations.
889 reset: function(models, options) {
890 options = options ? _.clone(options) : {};
891 for (var i = 0; i < this.models.length; i++) {
892 this._removeReference(this.models[i], options);
894 options.previousModels = this.models;
896 models = this.add(models, _.extend({silent: true}, options));
897 if (!options.silent) this.trigger('reset', this, options);
901 // Add a model to the end of the collection.
902 push: function(model, options) {
903 return this.add(model, _.extend({at: this.length}, options));
906 // Remove a model from the end of the collection.
907 pop: function(options) {
908 var model = this.at(this.length - 1);
909 this.remove(model, options);
913 // Add a model to the beginning of the collection.
914 unshift: function(model, options) {
915 return this.add(model, _.extend({at: 0}, options));
918 // Remove a model from the beginning of the collection.
919 shift: function(options) {
920 var model = this.at(0);
921 this.remove(model, options);
925 // Slice out a sub-array of models from the collection.
927 return slice.apply(this.models, arguments);
930 // Get a model from the set by id.
932 if (obj == null) return void 0;
933 var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
934 return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
937 // Get the model at the given index.
938 at: function(index) {
939 if (index < 0) index += this.length;
940 return this.models[index];
943 // Return models with matching attributes. Useful for simple cases of
945 where: function(attrs, first) {
946 var matches = _.matches(attrs);
947 return this[first ? 'find' : 'filter'](function(model) {
948 return matches(model.attributes);
952 // Return the first model with matching attributes. Useful for simple cases
954 findWhere: function(attrs) {
955 return this.where(attrs, true);
958 // Force the collection to re-sort itself. You don't need to call this under
959 // normal circumstances, as the set will maintain sort order as each item
961 sort: function(options) {
962 if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
963 options || (options = {});
965 // Run sort based on type of `comparator`.
966 if (_.isString(this.comparator) || this.comparator.length === 1) {
967 this.models = this.sortBy(this.comparator, this);
969 this.models.sort(_.bind(this.comparator, this));
972 if (!options.silent) this.trigger('sort', this, options);
976 // Pluck an attribute from each model in the collection.
977 pluck: function(attr) {
978 return _.invoke(this.models, 'get', attr);
981 // Fetch the default set of models for this collection, resetting the
982 // collection when they arrive. If `reset: true` is passed, the response
983 // data will be passed through the `reset` method instead of `set`.
984 fetch: function(options) {
985 options = options ? _.clone(options) : {};
986 if (options.parse === void 0) options.parse = true;
987 var success = options.success;
988 var collection = this;
989 options.success = function(resp) {
990 var method = options.reset ? 'reset' : 'set';
991 collection[method](resp, options);
992 if (success) success.call(options.context, collection, resp, options);
993 collection.trigger('sync', collection, resp, options);
995 wrapError(this, options);
996 return this.sync('read', this, options);
999 // Create a new instance of a model in this collection. Add the model to the
1000 // collection immediately, unless `wait: true` is passed, in which case we
1001 // wait for the server to agree.
1002 create: function(model, options) {
1003 options = options ? _.clone(options) : {};
1004 var wait = options.wait;
1005 if (!(model = this._prepareModel(model, options))) return false;
1006 if (!wait) this.add(model, options);
1007 var collection = this;
1008 var success = options.success;
1009 options.success = function(model, resp, callbackOpts) {
1010 if (wait) collection.add(model, callbackOpts);
1011 if (success) success.call(callbackOpts.context, model, resp, callbackOpts);
1013 model.save(null, options);
1017 // **parse** converts a response into a list of models to be added to the
1018 // collection. The default implementation is just to pass it through.
1019 parse: function(resp, options) {
1023 // Create a new collection with an identical list of models as this one.
1025 return new this.constructor(this.models, {
1027 comparator: this.comparator
1031 // Define how to uniquely identify models in the collection.
1032 modelId: function (attrs) {
1033 return attrs[this.model.prototype.idAttribute || 'id'];
1036 // Private method to reset all internal state. Called when the collection
1037 // is first initialized or reset.
1038 _reset: function() {
1044 // Prepare a hash of attributes (or other model) to be added to this
1046 _prepareModel: function(attrs, options) {
1047 if (this._isModel(attrs)) {
1048 if (!attrs.collection) attrs.collection = this;
1051 options = options ? _.clone(options) : {};
1052 options.collection = this;
1053 var model = new this.model(attrs, options);
1054 if (!model.validationError) return model;
1055 this.trigger('invalid', this, model.validationError, options);
1059 // Method for checking whether an object should be considered a model for
1060 // the purposes of adding to the collection.
1061 _isModel: function (model) {
1062 return model instanceof Model;
1065 // Internal method to create a model's ties to a collection.
1066 _addReference: function(model, options) {
1067 this._byId[model.cid] = model;
1068 var id = this.modelId(model.attributes);
1069 if (id != null) this._byId[id] = model;
1070 model.on('all', this._onModelEvent, this);
1073 // Internal method to sever a model's ties to a collection.
1074 _removeReference: function(model, options) {
1075 if (this === model.collection) delete model.collection;
1076 model.off('all', this._onModelEvent, this);
1079 // Internal method called every time a model in the set fires an event.
1080 // Sets need to update their indexes when models change ids. All other
1081 // events simply proxy through. "add" and "remove" events that originate
1082 // in other collections are ignored.
1083 _onModelEvent: function(event, model, collection, options) {
1084 if ((event === 'add' || event === 'remove') && collection !== this) return;
1085 if (event === 'destroy') this.remove(model, options);
1086 if (event === 'change') {
1087 var prevId = this.modelId(model.previousAttributes());
1088 var id = this.modelId(model.attributes);
1089 if (prevId !== id) {
1090 if (prevId != null) delete this._byId[prevId];
1091 if (id != null) this._byId[id] = model;
1094 this.trigger.apply(this, arguments);
1099 // Underscore methods that we want to implement on the Collection.
1100 // 90% of the core usefulness of Backbone Collections is actually implemented
1102 var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4,
1103 foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3,
1104 select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 2,
1105 contains: 2, invoke: 2, max: 3, min: 3, toArray: 1, size: 1, first: 3,
1106 head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
1107 without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
1108 isEmpty: 1, chain: 1, sample: 3, partition: 3 };
1110 // Mix in each Underscore method as a proxy to `Collection#models`.
1111 addUnderscoreMethods(Collection, collectionMethods, 'models');
1113 // Underscore methods that take a property name as an argument.
1114 var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
1116 // Use attributes instead of properties.
1117 _.each(attributeMethods, function(method) {
1118 if (!_[method]) return;
1119 Collection.prototype[method] = function(value, context) {
1120 var iterator = _.isFunction(value) ? value : function(model) {
1121 return model.get(value);
1123 return _[method](this.models, iterator, context);
1130 // Backbone Views are almost more convention than they are actual code. A View
1131 // is simply a JavaScript object that represents a logical chunk of UI in the
1132 // DOM. This might be a single item, an entire list, a sidebar or panel, or
1133 // even the surrounding frame which wraps your whole app. Defining a chunk of
1134 // UI as a **View** allows you to define your DOM events declaratively, without
1135 // having to worry about render order ... and makes it easy for the view to
1136 // react to specific changes in the state of your models.
1138 // Creating a Backbone.View creates its initial element outside of the DOM,
1139 // if an existing element is not provided...
1140 var View = Backbone.View = function(options) {
1141 this.cid = _.uniqueId('view');
1142 options || (options = {});
1143 _.extend(this, _.pick(options, viewOptions));
1144 this._ensureElement();
1145 this.initialize.apply(this, arguments);
1148 // Cached regex to split keys for `delegate`.
1149 var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1151 // List of view options to be merged as properties.
1152 var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1154 // Set up all inheritable **Backbone.View** properties and methods.
1155 _.extend(View.prototype, Events, {
1157 // The default `tagName` of a View's element is `"div"`.
1160 // jQuery delegate for element lookup, scoped to DOM elements within the
1161 // current view. This should be preferred to global lookups where possible.
1162 $: function(selector) {
1163 return this.$el.find(selector);
1166 // Initialize is an empty function by default. Override it with your own
1167 // initialization logic.
1168 initialize: function(){},
1170 // **render** is the core function that your view should override, in order
1171 // to populate its element (`this.el`), with the appropriate HTML. The
1172 // convention is for **render** to always return `this`.
1173 render: function() {
1177 // Remove this view by taking the element out of the DOM, and removing any
1178 // applicable Backbone.Events listeners.
1179 remove: function() {
1180 this._removeElement();
1181 this.stopListening();
1185 // Remove this view's element from the document and all event listeners
1186 // attached to it. Exposed for subclasses using an alternative DOM
1187 // manipulation API.
1188 _removeElement: function() {
1192 // Change the view's element (`this.el` property) and re-delegate the
1193 // view's events on the new element.
1194 setElement: function(element) {
1195 this.undelegateEvents();
1196 this._setElement(element);
1197 this.delegateEvents();
1201 // Creates the `this.el` and `this.$el` references for this view using the
1202 // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
1203 // context or an element. Subclasses can override this to utilize an
1204 // alternative DOM manipulation API and are only required to set the
1205 // `this.el` property.
1206 _setElement: function(el) {
1207 this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
1208 this.el = this.$el[0];
1211 // Set callbacks, where `this.events` is a hash of
1213 // *{"event selector": "callback"}*
1216 // 'mousedown .title': 'edit',
1217 // 'click .button': 'save',
1218 // 'click .open': function(e) { ... }
1221 // pairs. Callbacks will be bound to the view, with `this` set properly.
1222 // Uses event delegation for efficiency.
1223 // Omitting the selector binds the event to `this.el`.
1224 delegateEvents: function(events) {
1225 if (!(events || (events = _.result(this, 'events')))) return this;
1226 this.undelegateEvents();
1227 for (var key in events) {
1228 var method = events[key];
1229 if (!_.isFunction(method)) method = this[events[key]];
1230 if (!method) continue;
1231 var match = key.match(delegateEventSplitter);
1232 this.delegate(match[1], match[2], _.bind(method, this));
1237 // Add a single event listener to the view's element (or a child element
1238 // using `selector`). This only works for delegate-able events: not `focus`,
1239 // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
1240 delegate: function(eventName, selector, listener) {
1241 this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
1244 // Clears all callbacks previously bound to the view by `delegateEvents`.
1245 // You usually don't need to use this, but may wish to if you have multiple
1246 // Backbone views attached to the same DOM element.
1247 undelegateEvents: function() {
1248 if (this.$el) this.$el.off('.delegateEvents' + this.cid);
1252 // A finer-grained `undelegateEvents` for removing a single delegated event.
1253 // `selector` and `listener` are both optional.
1254 undelegate: function(eventName, selector, listener) {
1255 this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
1258 // Produces a DOM element to be assigned to your view. Exposed for
1259 // subclasses using an alternative DOM manipulation API.
1260 _createElement: function(tagName) {
1261 return document.createElement(tagName);
1264 // Ensure that the View has a DOM element to render into.
1265 // If `this.el` is a string, pass it through `$()`, take the first
1266 // matching element, and re-assign it to `el`. Otherwise, create
1267 // an element from the `id`, `className` and `tagName` properties.
1268 _ensureElement: function() {
1270 var attrs = _.extend({}, _.result(this, 'attributes'));
1271 if (this.id) attrs.id = _.result(this, 'id');
1272 if (this.className) attrs['class'] = _.result(this, 'className');
1273 this.setElement(this._createElement(_.result(this, 'tagName')));
1274 this._setAttributes(attrs);
1276 this.setElement(_.result(this, 'el'));
1280 // Set attributes from a hash on this view's element. Exposed for
1281 // subclasses using an alternative DOM manipulation API.
1282 _setAttributes: function(attributes) {
1283 this.$el.attr(attributes);
1291 // Override this function to change the manner in which Backbone persists
1292 // models to the server. You will be passed the type of request, and the
1293 // model in question. By default, makes a RESTful Ajax request
1294 // to the model's `url()`. Some possible customizations could be:
1296 // * Use `setTimeout` to batch rapid-fire updates into a single request.
1297 // * Send up the models as XML instead of JSON.
1298 // * Persist models via WebSockets instead of Ajax.
1300 // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1301 // as `POST`, with a `_method` parameter containing the true HTTP method,
1302 // as well as all requests with the body as `application/x-www-form-urlencoded`
1303 // instead of `application/json` with the model in a param named `model`.
1304 // Useful when interfacing with server-side languages like **PHP** that make
1305 // it difficult to read the body of `PUT` requests.
1306 Backbone.sync = function(method, model, options) {
1307 var type = methodMap[method];
1309 // Default options, unless specified.
1310 _.defaults(options || (options = {}), {
1311 emulateHTTP: Backbone.emulateHTTP,
1312 emulateJSON: Backbone.emulateJSON
1315 // Default JSON-request options.
1316 var params = {type: type, dataType: 'json'};
1318 // Ensure that we have a URL.
1320 params.url = _.result(model, 'url') || urlError();
1323 // Ensure that we have the appropriate request data.
1324 if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1325 params.contentType = 'application/json';
1326 params.data = JSON.stringify(options.attrs || model.toJSON(options));
1329 // For older servers, emulate JSON by encoding the request into an HTML-form.
1330 if (options.emulateJSON) {
1331 params.contentType = 'application/x-www-form-urlencoded';
1332 params.data = params.data ? {model: params.data} : {};
1335 // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1336 // And an `X-HTTP-Method-Override` header.
1337 if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1338 params.type = 'POST';
1339 if (options.emulateJSON) params.data._method = type;
1340 var beforeSend = options.beforeSend;
1341 options.beforeSend = function(xhr) {
1342 xhr.setRequestHeader('X-HTTP-Method-Override', type);
1343 if (beforeSend) return beforeSend.apply(this, arguments);
1347 // Don't process data on a non-GET request.
1348 if (params.type !== 'GET' && !options.emulateJSON) {
1349 params.processData = false;
1352 // Pass along `textStatus` and `errorThrown` from jQuery.
1353 var error = options.error;
1354 options.error = function(xhr, textStatus, errorThrown) {
1355 options.textStatus = textStatus;
1356 options.errorThrown = errorThrown;
1357 if (error) error.call(options.context, xhr, textStatus, errorThrown);
1360 // Make the request, allowing the user to override any Ajax options.
1361 var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1362 model.trigger('request', model, xhr, options);
1366 // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1375 // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1376 // Override this if you'd like to use a different library.
1377 Backbone.ajax = function() {
1378 return Backbone.$.ajax.apply(Backbone.$, arguments);
1384 // Routers map faux-URLs to actions, and fire events when routes are
1385 // matched. Creating a new one sets its `routes` hash, if not set statically.
1386 var Router = Backbone.Router = function(options) {
1387 options || (options = {});
1388 if (options.routes) this.routes = options.routes;
1390 this.initialize.apply(this, arguments);
1393 // Cached regular expressions for matching named param parts and splatted
1394 // parts of route strings.
1395 var optionalParam = /\((.*?)\)/g;
1396 var namedParam = /(\(\?)?:\w+/g;
1397 var splatParam = /\*\w+/g;
1398 var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1400 // Set up all inheritable **Backbone.Router** properties and methods.
1401 _.extend(Router.prototype, Events, {
1403 // Initialize is an empty function by default. Override it with your own
1404 // initialization logic.
1405 initialize: function(){},
1407 // Manually bind a single named route to a callback. For example:
1409 // this.route('search/:query/p:num', 'search', function(query, num) {
1413 route: function(route, name, callback) {
1414 if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1415 if (_.isFunction(name)) {
1419 if (!callback) callback = this[name];
1421 Backbone.history.route(route, function(fragment) {
1422 var args = router._extractParameters(route, fragment);
1423 if (router.execute(callback, args, name) !== false) {
1424 router.trigger.apply(router, ['route:' + name].concat(args));
1425 router.trigger('route', name, args);
1426 Backbone.history.trigger('route', router, name, args);
1432 // Execute a route handler with the provided parameters. This is an
1433 // excellent place to do pre-route setup or post-route cleanup.
1434 execute: function(callback, args, name) {
1435 if (callback) callback.apply(this, args);
1438 // Simple proxy to `Backbone.history` to save a fragment into the history.
1439 navigate: function(fragment, options) {
1440 Backbone.history.navigate(fragment, options);
1444 // Bind all defined routes to `Backbone.history`. We have to reverse the
1445 // order of the routes here to support behavior where the most general
1446 // routes can be defined at the bottom of the route map.
1447 _bindRoutes: function() {
1448 if (!this.routes) return;
1449 this.routes = _.result(this, 'routes');
1450 var route, routes = _.keys(this.routes);
1451 while ((route = routes.pop()) != null) {
1452 this.route(route, this.routes[route]);
1456 // Convert a route string into a regular expression, suitable for matching
1457 // against the current location hash.
1458 _routeToRegExp: function(route) {
1459 route = route.replace(escapeRegExp, '\\$&')
1460 .replace(optionalParam, '(?:$1)?')
1461 .replace(namedParam, function(match, optional) {
1462 return optional ? match : '([^/?]+)';
1464 .replace(splatParam, '([^?]*?)');
1465 return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
1468 // Given a route, and a URL fragment that it matches, return the array of
1469 // extracted decoded parameters. Empty or unmatched parameters will be
1470 // treated as `null` to normalize cross-browser behavior.
1471 _extractParameters: function(route, fragment) {
1472 var params = route.exec(fragment).slice(1);
1473 return _.map(params, function(param, i) {
1474 // Don't decode the search params.
1475 if (i === params.length - 1) return param || null;
1476 return param ? decodeURIComponent(param) : null;
1485 // Handles cross-browser history management, based on either
1486 // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1487 // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1488 // and URL fragments. If the browser supports neither (old IE, natch),
1489 // falls back to polling.
1490 var History = Backbone.History = function() {
1492 _.bindAll(this, 'checkUrl');
1494 // Ensure that `History` can be used outside of the browser.
1495 if (typeof window !== 'undefined') {
1496 this.location = window.location;
1497 this.history = window.history;
1501 // Cached regex for stripping a leading hash/slash and trailing space.
1502 var routeStripper = /^[#\/]|\s+$/g;
1504 // Cached regex for stripping leading and trailing slashes.
1505 var rootStripper = /^\/+|\/+$/g;
1507 // Cached regex for stripping urls of hash.
1508 var pathStripper = /#.*$/;
1510 // Has the history handling already been started?
1511 History.started = false;
1513 // Set up all inheritable **Backbone.History** properties and methods.
1514 _.extend(History.prototype, Events, {
1516 // The default interval to poll for hash changes, if necessary, is
1517 // twenty times a second.
1520 // Are we at the app root?
1521 atRoot: function() {
1522 var path = this.location.pathname.replace(/[^\/]$/, '$&/');
1523 return path === this.root && !this.getSearch();
1526 // Unicode characters in `location.pathname` are percent encoded so they're
1527 // decoded for comparison. `%25` should not be decoded since it may be part
1528 // of an encoded parameter.
1529 decodeFragment: function(fragment) {
1530 return decodeURI(fragment.replace(/%25/g, '%2525'));
1533 // In IE6, the hash fragment and search params are incorrect if the
1534 // fragment contains `?`.
1535 getSearch: function() {
1536 var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
1537 return match ? match[0] : '';
1540 // Gets the true hash value. Cannot use location.hash directly due to bug
1541 // in Firefox where location.hash will always be decoded.
1542 getHash: function(window) {
1543 var match = (window || this).location.href.match(/#(.*)$/);
1544 return match ? match[1] : '';
1547 // Get the pathname and search params, without the root.
1548 getPath: function() {
1549 var path = this.decodeFragment(
1550 this.location.pathname + this.getSearch()
1552 var root = this.root.slice(0, -1);
1553 if (!path.indexOf(root)) path = path.slice(root.length);
1554 return path.charAt(0) === '/' ? path.slice(1) : path;
1557 // Get the cross-browser normalized URL fragment from the path or hash.
1558 getFragment: function(fragment) {
1559 if (fragment == null) {
1560 if (this._usePushState || !this._wantsHashChange) {
1561 fragment = this.getPath();
1563 fragment = this.getHash();
1566 return fragment.replace(routeStripper, '');
1569 // Start the hash change handling, returning `true` if the current URL matches
1570 // an existing route, and `false` otherwise.
1571 start: function(options) {
1572 if (History.started) throw new Error('Backbone.history has already been started');
1573 History.started = true;
1575 // Figure out the initial configuration. Do we need an iframe?
1576 // Is pushState desired ... is it available?
1577 this.options = _.extend({root: '/'}, this.options, options);
1578 this.root = this.options.root;
1579 this._wantsHashChange = this.options.hashChange !== false;
1580 this._hasHashChange = 'onhashchange' in window;
1581 this._useHashChange = this._wantsHashChange && this._hasHashChange;
1582 this._wantsPushState = !!this.options.pushState;
1583 this._hasPushState = !!(this.history && this.history.pushState);
1584 this._usePushState = this._wantsPushState && this._hasPushState;
1585 this.fragment = this.getFragment();
1587 // Normalize root to always include a leading and trailing slash.
1588 this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1590 // Transition from hashChange to pushState or vice versa if both are
1592 if (this._wantsHashChange && this._wantsPushState) {
1594 // If we've started off with a route from a `pushState`-enabled
1595 // browser, but we're currently in a browser that doesn't support it...
1596 if (!this._hasPushState && !this.atRoot()) {
1597 var root = this.root.slice(0, -1) || '/';
1598 this.location.replace(root + '#' + this.getPath());
1599 // Return immediately as browser will do redirect to new url
1602 // Or if we've started out with a hash-based route, but we're currently
1603 // in a browser where it could be `pushState`-based instead...
1604 } else if (this._hasPushState && this.atRoot()) {
1605 this.navigate(this.getHash(), {replace: true});
1610 // Proxy an iframe to handle location events if the browser doesn't
1611 // support the `hashchange` event, HTML5 history, or the user wants
1612 // `hashChange` but not `pushState`.
1613 if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
1614 var iframe = document.createElement('iframe');
1615 iframe.src = 'javascript:0';
1616 iframe.style.display = 'none';
1617 iframe.tabIndex = -1;
1618 var body = document.body;
1619 // Using `appendChild` will throw on IE < 9 if the document is not ready.
1620 this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow;
1621 this.iframe.document.open().close();
1622 this.iframe.location.hash = '#' + this.fragment;
1625 // Add a cross-platform `addEventListener` shim for older browsers.
1626 var addEventListener = window.addEventListener || function (eventName, listener) {
1627 return attachEvent('on' + eventName, listener);
1630 // Depending on whether we're using pushState or hashes, and whether
1631 // 'onhashchange' is supported, determine how we check the URL state.
1632 if (this._usePushState) {
1633 addEventListener('popstate', this.checkUrl, false);
1634 } else if (this._useHashChange && !this.iframe) {
1635 addEventListener('hashchange', this.checkUrl, false);
1636 } else if (this._wantsHashChange) {
1637 this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1640 if (!this.options.silent) return this.loadUrl();
1643 // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1644 // but possibly useful for unit testing Routers.
1646 // Add a cross-platform `removeEventListener` shim for older browsers.
1647 var removeEventListener = window.removeEventListener || function (eventName, listener) {
1648 return detachEvent('on' + eventName, listener);
1651 // Remove window listeners.
1652 if (this._usePushState) {
1653 removeEventListener('popstate', this.checkUrl, false);
1654 } else if (this._useHashChange && !this.iframe) {
1655 removeEventListener('hashchange', this.checkUrl, false);
1658 // Clean up the iframe if necessary.
1660 document.body.removeChild(this.iframe.frameElement);
1664 // Some environments will throw when clearing an undefined interval.
1665 if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
1666 History.started = false;
1669 // Add a route to be tested when the fragment changes. Routes added later
1670 // may override previous routes.
1671 route: function(route, callback) {
1672 this.handlers.unshift({route: route, callback: callback});
1675 // Checks the current URL to see if it has changed, and if it has,
1676 // calls `loadUrl`, normalizing across the hidden iframe.
1677 checkUrl: function(e) {
1678 var current = this.getFragment();
1680 // If the user pressed the back button, the iframe's hash will have
1681 // changed and we should use that for comparison.
1682 if (current === this.fragment && this.iframe) {
1683 current = this.getHash(this.iframe);
1686 if (current === this.fragment) return false;
1687 if (this.iframe) this.navigate(current);
1691 // Attempt to load the current URL fragment. If a route succeeds with a
1692 // match, returns `true`. If no defined routes matches the fragment,
1694 loadUrl: function(fragment) {
1695 fragment = this.fragment = this.getFragment(fragment);
1696 return _.any(this.handlers, function(handler) {
1697 if (handler.route.test(fragment)) {
1698 handler.callback(fragment);
1704 // Save a fragment into the hash history, or replace the URL state if the
1705 // 'replace' option is passed. You are responsible for properly URL-encoding
1706 // the fragment in advance.
1708 // The options object can contain `trigger: true` if you wish to have the
1709 // route callback be fired (not usually desirable), or `replace: true`, if
1710 // you wish to modify the current URL without adding an entry to the history.
1711 navigate: function(fragment, options) {
1712 if (!History.started) return false;
1713 if (!options || options === true) options = {trigger: !!options};
1715 // Normalize the fragment.
1716 fragment = this.getFragment(fragment || '');
1718 // Don't include a trailing slash on the root.
1719 var root = this.root;
1720 if (fragment === '' || fragment.charAt(0) === '?') {
1721 root = root.slice(0, -1) || '/';
1723 var url = root + fragment;
1725 // Strip the hash and decode for matching.
1726 fragment = this.decodeFragment(fragment.replace(pathStripper, ''));
1728 if (this.fragment === fragment) return;
1729 this.fragment = fragment;
1731 // If pushState is available, we use it to set the fragment as a real URL.
1732 if (this._usePushState) {
1733 this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1735 // If hash changes haven't been explicitly disabled, update the hash
1736 // fragment to store history.
1737 } else if (this._wantsHashChange) {
1738 this._updateHash(this.location, fragment, options.replace);
1739 if (this.iframe && (fragment !== this.getHash(this.iframe))) {
1740 // Opening and closing the iframe tricks IE7 and earlier to push a
1741 // history entry on hash-tag change. When replace is true, we don't
1743 if (!options.replace) this.iframe.document.open().close();
1744 this._updateHash(this.iframe.location, fragment, options.replace);
1747 // If you've told us that you explicitly don't want fallback hashchange-
1748 // based history, then `navigate` becomes a page refresh.
1750 return this.location.assign(url);
1752 if (options.trigger) return this.loadUrl(fragment);
1755 // Update the hash location, either replacing the current entry, or adding
1756 // a new one to the browser history.
1757 _updateHash: function(location, fragment, replace) {
1759 var href = location.href.replace(/(javascript:|#).*$/, '');
1760 location.replace(href + '#' + fragment);
1762 // Some browsers require that `hash` contains a leading #.
1763 location.hash = '#' + fragment;
1769 // Create the default Backbone.history.
1770 Backbone.history = new History;
1775 // Helper function to correctly set up the prototype chain, for subclasses.
1776 // Similar to `goog.inherits`, but uses a hash of prototype properties and
1777 // class properties to be extended.
1778 var extend = function(protoProps, staticProps) {
1782 // The constructor function for the new subclass is either defined by you
1783 // (the "constructor" property in your `extend` definition), or defaulted
1784 // by us to simply call the parent's constructor.
1785 if (protoProps && _.has(protoProps, 'constructor')) {
1786 child = protoProps.constructor;
1788 child = function(){ return parent.apply(this, arguments); };
1791 // Add static properties to the constructor function, if supplied.
1792 _.extend(child, parent, staticProps);
1794 // Set the prototype chain to inherit from `parent`, without calling
1795 // `parent`'s constructor function.
1796 var Surrogate = function(){ this.constructor = child; };
1797 Surrogate.prototype = parent.prototype;
1798 child.prototype = new Surrogate;
1800 // Add prototype properties (instance properties) to the subclass,
1802 if (protoProps) _.extend(child.prototype, protoProps);
1804 // Set a convenience property in case the parent's prototype is needed
1806 child.__super__ = parent.prototype;
1811 // Set up inheritance for the model, collection, router, view and history.
1812 Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1814 // Throw an error when a URL is needed, and none is supplied.
1815 var urlError = function() {
1816 throw new Error('A "url" property or function must be specified');
1819 // Wrap an optional error callback with a fallback error event.
1820 var wrapError = function(model, options) {
1821 var error = options.error;
1822 options.error = function(resp) {
1823 if (error) error.call(options.context, model, resp, options);
1824 model.trigger('error', model, resp, options);