balmet.com

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

backbone.js (77794B)


      1 //     Backbone.js 1.4.0
      2 
      3 //     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
      4 //     Backbone may be freely distributed under the MIT license.
      5 //     For all details and documentation:
      6 //     http://backbonejs.org
      7 
      8 (function(factory) {
      9 
     10   // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
     11   // We use `self` instead of `window` for `WebWorker` support.
     12   var root = typeof self == 'object' && self.self === self && self ||
     13             typeof global == 'object' && global.global === global && global;
     14 
     15   // Set up Backbone appropriately for the environment. Start with AMD.
     16   if (typeof define === 'function' && define.amd) {
     17     define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
     18       // Export global even in AMD case in case this script is loaded with
     19       // others that may still expect a global Backbone.
     20       root.Backbone = factory(root, exports, _, $);
     21     });
     22 
     23   // Next for Node.js or CommonJS. jQuery may not be needed as a module.
     24   } else if (typeof exports !== 'undefined') {
     25     var _ = require('underscore'), $;
     26     try { $ = require('jquery'); } catch (e) {}
     27     factory(root, exports, _, $);
     28 
     29   // Finally, as a browser global.
     30   } else {
     31     root.Backbone = factory(root, {}, root._, root.jQuery || root.Zepto || root.ender || root.$);
     32   }
     33 
     34 })(function(root, Backbone, _, $) {
     35 
     36   // Initial Setup
     37   // -------------
     38 
     39   // Save the previous value of the `Backbone` variable, so that it can be
     40   // restored later on, if `noConflict` is used.
     41   var previousBackbone = root.Backbone;
     42 
     43   // Create a local reference to a common array method we'll want to use later.
     44   var slice = Array.prototype.slice;
     45 
     46   // Current version of the library. Keep in sync with `package.json`.
     47   Backbone.VERSION = '1.4.0';
     48 
     49   // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
     50   // the `$` variable.
     51   Backbone.$ = $;
     52 
     53   // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
     54   // to its previous owner. Returns a reference to this Backbone object.
     55   Backbone.noConflict = function() {
     56     root.Backbone = previousBackbone;
     57     return this;
     58   };
     59 
     60   // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
     61   // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
     62   // set a `X-Http-Method-Override` header.
     63   Backbone.emulateHTTP = false;
     64 
     65   // Turn on `emulateJSON` to support legacy servers that can't deal with direct
     66   // `application/json` requests ... this will encode the body as
     67   // `application/x-www-form-urlencoded` instead and will send the model in a
     68   // form param named `model`.
     69   Backbone.emulateJSON = false;
     70 
     71   // Backbone.Events
     72   // ---------------
     73 
     74   // A module that can be mixed in to *any object* in order to provide it with
     75   // a custom event channel. You may bind a callback to an event with `on` or
     76   // remove with `off`; `trigger`-ing an event fires all callbacks in
     77   // succession.
     78   //
     79   //     var object = {};
     80   //     _.extend(object, Backbone.Events);
     81   //     object.on('expand', function(){ alert('expanded'); });
     82   //     object.trigger('expand');
     83   //
     84   var Events = Backbone.Events = {};
     85 
     86   // Regular expression used to split event strings.
     87   var eventSplitter = /\s+/;
     88 
     89   // A private global variable to share between listeners and listenees.
     90   var _listening;
     91 
     92   // Iterates over the standard `event, callback` (as well as the fancy multiple
     93   // space-separated events `"change blur", callback` and jQuery-style event
     94   // maps `{event: callback}`).
     95   var eventsApi = function(iteratee, events, name, callback, opts) {
     96     var i = 0, names;
     97     if (name && typeof name === 'object') {
     98       // Handle event maps.
     99       if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
    100       for (names = _.keys(name); i < names.length ; i++) {
    101         events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
    102       }
    103     } else if (name && eventSplitter.test(name)) {
    104       // Handle space-separated event names by delegating them individually.
    105       for (names = name.split(eventSplitter); i < names.length; i++) {
    106         events = iteratee(events, names[i], callback, opts);
    107       }
    108     } else {
    109       // Finally, standard events.
    110       events = iteratee(events, name, callback, opts);
    111     }
    112     return events;
    113   };
    114 
    115   // Bind an event to a `callback` function. Passing `"all"` will bind
    116   // the callback to all events fired.
    117   Events.on = function(name, callback, context) {
    118     this._events = eventsApi(onApi, this._events || {}, name, callback, {
    119       context: context,
    120       ctx: this,
    121       listening: _listening
    122     });
    123 
    124     if (_listening) {
    125       var listeners = this._listeners || (this._listeners = {});
    126       listeners[_listening.id] = _listening;
    127       // Allow the listening to use a counter, instead of tracking
    128       // callbacks for library interop
    129       _listening.interop = false;
    130     }
    131 
    132     return this;
    133   };
    134 
    135   // Inversion-of-control versions of `on`. Tell *this* object to listen to
    136   // an event in another object... keeping track of what it's listening to
    137   // for easier unbinding later.
    138   Events.listenTo = function(obj, name, callback) {
    139     if (!obj) return this;
    140     var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
    141     var listeningTo = this._listeningTo || (this._listeningTo = {});
    142     var listening = _listening = listeningTo[id];
    143 
    144     // This object is not listening to any other events on `obj` yet.
    145     // Setup the necessary references to track the listening callbacks.
    146     if (!listening) {
    147       this._listenId || (this._listenId = _.uniqueId('l'));
    148       listening = _listening = listeningTo[id] = new Listening(this, obj);
    149     }
    150 
    151     // Bind callbacks on obj.
    152     var error = tryCatchOn(obj, name, callback, this);
    153     _listening = void 0;
    154 
    155     if (error) throw error;
    156     // If the target obj is not Backbone.Events, track events manually.
    157     if (listening.interop) listening.on(name, callback);
    158 
    159     return this;
    160   };
    161 
    162   // The reducing API that adds a callback to the `events` object.
    163   var onApi = function(events, name, callback, options) {
    164     if (callback) {
    165       var handlers = events[name] || (events[name] = []);
    166       var context = options.context, ctx = options.ctx, listening = options.listening;
    167       if (listening) listening.count++;
    168 
    169       handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
    170     }
    171     return events;
    172   };
    173 
    174   // An try-catch guarded #on function, to prevent poisoning the global
    175   // `_listening` variable.
    176   var tryCatchOn = function(obj, name, callback, context) {
    177     try {
    178       obj.on(name, callback, context);
    179     } catch (e) {
    180       return e;
    181     }
    182   };
    183 
    184   // Remove one or many callbacks. If `context` is null, removes all
    185   // callbacks with that function. If `callback` is null, removes all
    186   // callbacks for the event. If `name` is null, removes all bound
    187   // callbacks for all events.
    188   Events.off = function(name, callback, context) {
    189     if (!this._events) return this;
    190     this._events = eventsApi(offApi, this._events, name, callback, {
    191       context: context,
    192       listeners: this._listeners
    193     });
    194 
    195     return this;
    196   };
    197 
    198   // Tell this object to stop listening to either specific events ... or
    199   // to every object it's currently listening to.
    200   Events.stopListening = function(obj, name, callback) {
    201     var listeningTo = this._listeningTo;
    202     if (!listeningTo) return this;
    203 
    204     var ids = obj ? [obj._listenId] : _.keys(listeningTo);
    205     for (var i = 0; i < ids.length; i++) {
    206       var listening = listeningTo[ids[i]];
    207 
    208       // If listening doesn't exist, this object is not currently
    209       // listening to obj. Break out early.
    210       if (!listening) break;
    211 
    212       listening.obj.off(name, callback, this);
    213       if (listening.interop) listening.off(name, callback);
    214     }
    215     if (_.isEmpty(listeningTo)) this._listeningTo = void 0;
    216 
    217     return this;
    218   };
    219 
    220   // The reducing API that removes a callback from the `events` object.
    221   var offApi = function(events, name, callback, options) {
    222     if (!events) return;
    223 
    224     var context = options.context, listeners = options.listeners;
    225     var i = 0, names;
    226 
    227     // Delete all event listeners and "drop" events.
    228     if (!name && !context && !callback) {
    229       for (names = _.keys(listeners); i < names.length; i++) {
    230         listeners[names[i]].cleanup();
    231       }
    232       return;
    233     }
    234 
    235     names = name ? [name] : _.keys(events);
    236     for (; i < names.length; i++) {
    237       name = names[i];
    238       var handlers = events[name];
    239 
    240       // Bail out if there are no events stored.
    241       if (!handlers) break;
    242 
    243       // Find any remaining events.
    244       var remaining = [];
    245       for (var j = 0; j < handlers.length; j++) {
    246         var handler = handlers[j];
    247         if (
    248           callback && callback !== handler.callback &&
    249             callback !== handler.callback._callback ||
    250               context && context !== handler.context
    251         ) {
    252           remaining.push(handler);
    253         } else {
    254           var listening = handler.listening;
    255           if (listening) listening.off(name, callback);
    256         }
    257       }
    258 
    259       // Replace events if there are any remaining.  Otherwise, clean up.
    260       if (remaining.length) {
    261         events[name] = remaining;
    262       } else {
    263         delete events[name];
    264       }
    265     }
    266 
    267     return events;
    268   };
    269 
    270   // Bind an event to only be triggered a single time. After the first time
    271   // the callback is invoked, its listener will be removed. If multiple events
    272   // are passed in using the space-separated syntax, the handler will fire
    273   // once for each event, not once for a combination of all events.
    274   Events.once = function(name, callback, context) {
    275     // Map the event into a `{event: once}` object.
    276     var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
    277     if (typeof name === 'string' && context == null) callback = void 0;
    278     return this.on(events, callback, context);
    279   };
    280 
    281   // Inversion-of-control versions of `once`.
    282   Events.listenToOnce = function(obj, name, callback) {
    283     // Map the event into a `{event: once}` object.
    284     var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
    285     return this.listenTo(obj, events);
    286   };
    287 
    288   // Reduces the event callbacks into a map of `{event: onceWrapper}`.
    289   // `offer` unbinds the `onceWrapper` after it has been called.
    290   var onceMap = function(map, name, callback, offer) {
    291     if (callback) {
    292       var once = map[name] = _.once(function() {
    293         offer(name, once);
    294         callback.apply(this, arguments);
    295       });
    296       once._callback = callback;
    297     }
    298     return map;
    299   };
    300 
    301   // Trigger one or many events, firing all bound callbacks. Callbacks are
    302   // passed the same arguments as `trigger` is, apart from the event name
    303   // (unless you're listening on `"all"`, which will cause your callback to
    304   // receive the true name of the event as the first argument).
    305   Events.trigger = function(name) {
    306     if (!this._events) return this;
    307 
    308     var length = Math.max(0, arguments.length - 1);
    309     var args = Array(length);
    310     for (var i = 0; i < length; i++) args[i] = arguments[i + 1];
    311 
    312     eventsApi(triggerApi, this._events, name, void 0, args);
    313     return this;
    314   };
    315 
    316   // Handles triggering the appropriate event callbacks.
    317   var triggerApi = function(objEvents, name, callback, args) {
    318     if (objEvents) {
    319       var events = objEvents[name];
    320       var allEvents = objEvents.all;
    321       if (events && allEvents) allEvents = allEvents.slice();
    322       if (events) triggerEvents(events, args);
    323       if (allEvents) triggerEvents(allEvents, [name].concat(args));
    324     }
    325     return objEvents;
    326   };
    327 
    328   // A difficult-to-believe, but optimized internal dispatch function for
    329   // triggering events. Tries to keep the usual cases speedy (most internal
    330   // Backbone events have 3 arguments).
    331   var triggerEvents = function(events, args) {
    332     var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
    333     switch (args.length) {
    334       case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
    335       case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
    336       case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
    337       case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
    338       default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
    339     }
    340   };
    341 
    342   // A listening class that tracks and cleans up memory bindings
    343   // when all callbacks have been offed.
    344   var Listening = function(listener, obj) {
    345     this.id = listener._listenId;
    346     this.listener = listener;
    347     this.obj = obj;
    348     this.interop = true;
    349     this.count = 0;
    350     this._events = void 0;
    351   };
    352 
    353   Listening.prototype.on = Events.on;
    354 
    355   // Offs a callback (or several).
    356   // Uses an optimized counter if the listenee uses Backbone.Events.
    357   // Otherwise, falls back to manual tracking to support events
    358   // library interop.
    359   Listening.prototype.off = function(name, callback) {
    360     var cleanup;
    361     if (this.interop) {
    362       this._events = eventsApi(offApi, this._events, name, callback, {
    363         context: void 0,
    364         listeners: void 0
    365       });
    366       cleanup = !this._events;
    367     } else {
    368       this.count--;
    369       cleanup = this.count === 0;
    370     }
    371     if (cleanup) this.cleanup();
    372   };
    373 
    374   // Cleans up memory bindings between the listener and the listenee.
    375   Listening.prototype.cleanup = function() {
    376     delete this.listener._listeningTo[this.obj._listenId];
    377     if (!this.interop) delete this.obj._listeners[this.id];
    378   };
    379 
    380   // Aliases for backwards compatibility.
    381   Events.bind   = Events.on;
    382   Events.unbind = Events.off;
    383 
    384   // Allow the `Backbone` object to serve as a global event bus, for folks who
    385   // want global "pubsub" in a convenient place.
    386   _.extend(Backbone, Events);
    387 
    388   // Backbone.Model
    389   // --------------
    390 
    391   // Backbone **Models** are the basic data object in the framework --
    392   // frequently representing a row in a table in a database on your server.
    393   // A discrete chunk of data and a bunch of useful, related methods for
    394   // performing computations and transformations on that data.
    395 
    396   // Create a new model with the specified attributes. A client id (`cid`)
    397   // is automatically generated and assigned for you.
    398   var Model = Backbone.Model = function(attributes, options) {
    399     var attrs = attributes || {};
    400     options || (options = {});
    401     this.preinitialize.apply(this, arguments);
    402     this.cid = _.uniqueId(this.cidPrefix);
    403     this.attributes = {};
    404     if (options.collection) this.collection = options.collection;
    405     if (options.parse) attrs = this.parse(attrs, options) || {};
    406     var defaults = _.result(this, 'defaults');
    407     attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    408     this.set(attrs, options);
    409     this.changed = {};
    410     this.initialize.apply(this, arguments);
    411   };
    412 
    413   // Attach all inheritable methods to the Model prototype.
    414   _.extend(Model.prototype, Events, {
    415 
    416     // A hash of attributes whose current and previous value differ.
    417     changed: null,
    418 
    419     // The value returned during the last failed validation.
    420     validationError: null,
    421 
    422     // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    423     // CouchDB users may want to set this to `"_id"`.
    424     idAttribute: 'id',
    425 
    426     // The prefix is used to create the client id which is used to identify models locally.
    427     // You may want to override this if you're experiencing name clashes with model ids.
    428     cidPrefix: 'c',
    429 
    430     // preinitialize is an empty function by default. You can override it with a function
    431     // or object.  preinitialize will run before any instantiation logic is run in the Model.
    432     preinitialize: function(){},
    433 
    434     // Initialize is an empty function by default. Override it with your own
    435     // initialization logic.
    436     initialize: function(){},
    437 
    438     // Return a copy of the model's `attributes` object.
    439     toJSON: function(options) {
    440       return _.clone(this.attributes);
    441     },
    442 
    443     // Proxy `Backbone.sync` by default -- but override this if you need
    444     // custom syncing semantics for *this* particular model.
    445     sync: function() {
    446       return Backbone.sync.apply(this, arguments);
    447     },
    448 
    449     // Get the value of an attribute.
    450     get: function(attr) {
    451       return this.attributes[attr];
    452     },
    453 
    454     // Get the HTML-escaped value of an attribute.
    455     escape: function(attr) {
    456       return _.escape(this.get(attr));
    457     },
    458 
    459     // Returns `true` if the attribute contains a value that is not null
    460     // or undefined.
    461     has: function(attr) {
    462       return this.get(attr) != null;
    463     },
    464 
    465     // Special-cased proxy to underscore's `_.matches` method.
    466     matches: function(attrs) {
    467       return !!_.iteratee(attrs, this)(this.attributes);
    468     },
    469 
    470     // Set a hash of model attributes on the object, firing `"change"`. This is
    471     // the core primitive operation of a model, updating the data and notifying
    472     // anyone who needs to know about the change in state. The heart of the beast.
    473     set: function(key, val, options) {
    474       if (key == null) return this;
    475 
    476       // Handle both `"key", value` and `{key: value}` -style arguments.
    477       var attrs;
    478       if (typeof key === 'object') {
    479         attrs = key;
    480         options = val;
    481       } else {
    482         (attrs = {})[key] = val;
    483       }
    484 
    485       options || (options = {});
    486 
    487       // Run validation.
    488       if (!this._validate(attrs, options)) return false;
    489 
    490       // Extract attributes and options.
    491       var unset      = options.unset;
    492       var silent     = options.silent;
    493       var changes    = [];
    494       var changing   = this._changing;
    495       this._changing = true;
    496 
    497       if (!changing) {
    498         this._previousAttributes = _.clone(this.attributes);
    499         this.changed = {};
    500       }
    501 
    502       var current = this.attributes;
    503       var changed = this.changed;
    504       var prev    = this._previousAttributes;
    505 
    506       // For each `set` attribute, update or delete the current value.
    507       for (var attr in attrs) {
    508         val = attrs[attr];
    509         if (!_.isEqual(current[attr], val)) changes.push(attr);
    510         if (!_.isEqual(prev[attr], val)) {
    511           changed[attr] = val;
    512         } else {
    513           delete changed[attr];
    514         }
    515         unset ? delete current[attr] : current[attr] = val;
    516       }
    517 
    518       // Update the `id`.
    519       if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);
    520 
    521       // Trigger all relevant attribute changes.
    522       if (!silent) {
    523         if (changes.length) this._pending = options;
    524         for (var i = 0; i < changes.length; i++) {
    525           this.trigger('change:' + changes[i], this, current[changes[i]], options);
    526         }
    527       }
    528 
    529       // You might be wondering why there's a `while` loop here. Changes can
    530       // be recursively nested within `"change"` events.
    531       if (changing) return this;
    532       if (!silent) {
    533         while (this._pending) {
    534           options = this._pending;
    535           this._pending = false;
    536           this.trigger('change', this, options);
    537         }
    538       }
    539       this._pending = false;
    540       this._changing = false;
    541       return this;
    542     },
    543 
    544     // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    545     // if the attribute doesn't exist.
    546     unset: function(attr, options) {
    547       return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    548     },
    549 
    550     // Clear all attributes on the model, firing `"change"`.
    551     clear: function(options) {
    552       var attrs = {};
    553       for (var key in this.attributes) attrs[key] = void 0;
    554       return this.set(attrs, _.extend({}, options, {unset: true}));
    555     },
    556 
    557     // Determine if the model has changed since the last `"change"` event.
    558     // If you specify an attribute name, determine if that attribute has changed.
    559     hasChanged: function(attr) {
    560       if (attr == null) return !_.isEmpty(this.changed);
    561       return _.has(this.changed, attr);
    562     },
    563 
    564     // Return an object containing all the attributes that have changed, or
    565     // false if there are no changed attributes. Useful for determining what
    566     // parts of a view need to be updated and/or what attributes need to be
    567     // persisted to the server. Unset attributes will be set to undefined.
    568     // You can also pass an attributes object to diff against the model,
    569     // determining if there *would be* a change.
    570     changedAttributes: function(diff) {
    571       if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
    572       var old = this._changing ? this._previousAttributes : this.attributes;
    573       var changed = {};
    574       var hasChanged;
    575       for (var attr in diff) {
    576         var val = diff[attr];
    577         if (_.isEqual(old[attr], val)) continue;
    578         changed[attr] = val;
    579         hasChanged = true;
    580       }
    581       return hasChanged ? changed : false;
    582     },
    583 
    584     // Get the previous value of an attribute, recorded at the time the last
    585     // `"change"` event was fired.
    586     previous: function(attr) {
    587       if (attr == null || !this._previousAttributes) return null;
    588       return this._previousAttributes[attr];
    589     },
    590 
    591     // Get all of the attributes of the model at the time of the previous
    592     // `"change"` event.
    593     previousAttributes: function() {
    594       return _.clone(this._previousAttributes);
    595     },
    596 
    597     // Fetch the model from the server, merging the response with the model's
    598     // local attributes. Any changed attributes will trigger a "change" event.
    599     fetch: function(options) {
    600       options = _.extend({parse: true}, options);
    601       var model = this;
    602       var success = options.success;
    603       options.success = function(resp) {
    604         var serverAttrs = options.parse ? model.parse(resp, options) : resp;
    605         if (!model.set(serverAttrs, options)) return false;
    606         if (success) success.call(options.context, model, resp, options);
    607         model.trigger('sync', model, resp, options);
    608       };
    609       wrapError(this, options);
    610       return this.sync('read', this, options);
    611     },
    612 
    613     // Set a hash of model attributes, and sync the model to the server.
    614     // If the server returns an attributes hash that differs, the model's
    615     // state will be `set` again.
    616     save: function(key, val, options) {
    617       // Handle both `"key", value` and `{key: value}` -style arguments.
    618       var attrs;
    619       if (key == null || typeof key === 'object') {
    620         attrs = key;
    621         options = val;
    622       } else {
    623         (attrs = {})[key] = val;
    624       }
    625 
    626       options = _.extend({validate: true, parse: true}, options);
    627       var wait = options.wait;
    628 
    629       // If we're not waiting and attributes exist, save acts as
    630       // `set(attr).save(null, opts)` with validation. Otherwise, check if
    631       // the model will be valid when the attributes, if any, are set.
    632       if (attrs && !wait) {
    633         if (!this.set(attrs, options)) return false;
    634       } else if (!this._validate(attrs, options)) {
    635         return false;
    636       }
    637 
    638       // After a successful server-side save, the client is (optionally)
    639       // updated with the server-side state.
    640       var model = this;
    641       var success = options.success;
    642       var attributes = this.attributes;
    643       options.success = function(resp) {
    644         // Ensure attributes are restored during synchronous saves.
    645         model.attributes = attributes;
    646         var serverAttrs = options.parse ? model.parse(resp, options) : resp;
    647         if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
    648         if (serverAttrs && !model.set(serverAttrs, options)) return false;
    649         if (success) success.call(options.context, model, resp, options);
    650         model.trigger('sync', model, resp, options);
    651       };
    652       wrapError(this, options);
    653 
    654       // Set temporary attributes if `{wait: true}` to properly find new ids.
    655       if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
    656 
    657       var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
    658       if (method === 'patch' && !options.attrs) options.attrs = attrs;
    659       var xhr = this.sync(method, this, options);
    660 
    661       // Restore attributes.
    662       this.attributes = attributes;
    663 
    664       return xhr;
    665     },
    666 
    667     // Destroy this model on the server if it was already persisted.
    668     // Optimistically removes the model from its collection, if it has one.
    669     // If `wait: true` is passed, waits for the server to respond before removal.
    670     destroy: function(options) {
    671       options = options ? _.clone(options) : {};
    672       var model = this;
    673       var success = options.success;
    674       var wait = options.wait;
    675 
    676       var destroy = function() {
    677         model.stopListening();
    678         model.trigger('destroy', model, model.collection, options);
    679       };
    680 
    681       options.success = function(resp) {
    682         if (wait) destroy();
    683         if (success) success.call(options.context, model, resp, options);
    684         if (!model.isNew()) model.trigger('sync', model, resp, options);
    685       };
    686 
    687       var xhr = false;
    688       if (this.isNew()) {
    689         _.defer(options.success);
    690       } else {
    691         wrapError(this, options);
    692         xhr = this.sync('delete', this, options);
    693       }
    694       if (!wait) destroy();
    695       return xhr;
    696     },
    697 
    698     // Default URL for the model's representation on the server -- if you're
    699     // using Backbone's restful methods, override this to change the endpoint
    700     // that will be called.
    701     url: function() {
    702       var base =
    703         _.result(this, 'urlRoot') ||
    704         _.result(this.collection, 'url') ||
    705         urlError();
    706       if (this.isNew()) return base;
    707       var id = this.get(this.idAttribute);
    708       return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    709     },
    710 
    711     // **parse** converts a response into the hash of attributes to be `set` on
    712     // the model. The default implementation is just to pass the response along.
    713     parse: function(resp, options) {
    714       return resp;
    715     },
    716 
    717     // Create a new model with identical attributes to this one.
    718     clone: function() {
    719       return new this.constructor(this.attributes);
    720     },
    721 
    722     // A model is new if it has never been saved to the server, and lacks an id.
    723     isNew: function() {
    724       return !this.has(this.idAttribute);
    725     },
    726 
    727     // Check if the model is currently in a valid state.
    728     isValid: function(options) {
    729       return this._validate({}, _.extend({}, options, {validate: true}));
    730     },
    731 
    732     // Run validation against the next complete set of model attributes,
    733     // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    734     _validate: function(attrs, options) {
    735       if (!options.validate || !this.validate) return true;
    736       attrs = _.extend({}, this.attributes, attrs);
    737       var error = this.validationError = this.validate(attrs, options) || null;
    738       if (!error) return true;
    739       this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
    740       return false;
    741     }
    742 
    743   });
    744 
    745   // Backbone.Collection
    746   // -------------------
    747 
    748   // If models tend to represent a single row of data, a Backbone Collection is
    749   // more analogous to a table full of data ... or a small slice or page of that
    750   // table, or a collection of rows that belong together for a particular reason
    751   // -- all of the messages in this particular folder, all of the documents
    752   // belonging to this particular author, and so on. Collections maintain
    753   // indexes of their models, both in order, and for lookup by `id`.
    754 
    755   // Create a new **Collection**, perhaps to contain a specific type of `model`.
    756   // If a `comparator` is specified, the Collection will maintain
    757   // its models in sort order, as they're added and removed.
    758   var Collection = Backbone.Collection = function(models, options) {
    759     options || (options = {});
    760     this.preinitialize.apply(this, arguments);
    761     if (options.model) this.model = options.model;
    762     if (options.comparator !== void 0) this.comparator = options.comparator;
    763     this._reset();
    764     this.initialize.apply(this, arguments);
    765     if (models) this.reset(models, _.extend({silent: true}, options));
    766   };
    767 
    768   // Default options for `Collection#set`.
    769   var setOptions = {add: true, remove: true, merge: true};
    770   var addOptions = {add: true, remove: false};
    771 
    772   // Splices `insert` into `array` at index `at`.
    773   var splice = function(array, insert, at) {
    774     at = Math.min(Math.max(at, 0), array.length);
    775     var tail = Array(array.length - at);
    776     var length = insert.length;
    777     var i;
    778     for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
    779     for (i = 0; i < length; i++) array[i + at] = insert[i];
    780     for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
    781   };
    782 
    783   // Define the Collection's inheritable methods.
    784   _.extend(Collection.prototype, Events, {
    785 
    786     // The default model for a collection is just a **Backbone.Model**.
    787     // This should be overridden in most cases.
    788     model: Model,
    789 
    790 
    791     // preinitialize is an empty function by default. You can override it with a function
    792     // or object.  preinitialize will run before any instantiation logic is run in the Collection.
    793     preinitialize: function(){},
    794 
    795     // Initialize is an empty function by default. Override it with your own
    796     // initialization logic.
    797     initialize: function(){},
    798 
    799     // The JSON representation of a Collection is an array of the
    800     // models' attributes.
    801     toJSON: function(options) {
    802       return this.map(function(model) { return model.toJSON(options); });
    803     },
    804 
    805     // Proxy `Backbone.sync` by default.
    806     sync: function() {
    807       return Backbone.sync.apply(this, arguments);
    808     },
    809 
    810     // Add a model, or list of models to the set. `models` may be Backbone
    811     // Models or raw JavaScript objects to be converted to Models, or any
    812     // combination of the two.
    813     add: function(models, options) {
    814       return this.set(models, _.extend({merge: false}, options, addOptions));
    815     },
    816 
    817     // Remove a model, or a list of models from the set.
    818     remove: function(models, options) {
    819       options = _.extend({}, options);
    820       var singular = !_.isArray(models);
    821       models = singular ? [models] : models.slice();
    822       var removed = this._removeModels(models, options);
    823       if (!options.silent && removed.length) {
    824         options.changes = {added: [], merged: [], removed: removed};
    825         this.trigger('update', this, options);
    826       }
    827       return singular ? removed[0] : removed;
    828     },
    829 
    830     // Update a collection by `set`-ing a new list of models, adding new ones,
    831     // removing models that are no longer present, and merging models that
    832     // already exist in the collection, as necessary. Similar to **Model#set**,
    833     // the core operation for updating the data contained by the collection.
    834     set: function(models, options) {
    835       if (models == null) return;
    836 
    837       options = _.extend({}, setOptions, options);
    838       if (options.parse && !this._isModel(models)) {
    839         models = this.parse(models, options) || [];
    840       }
    841 
    842       var singular = !_.isArray(models);
    843       models = singular ? [models] : models.slice();
    844 
    845       var at = options.at;
    846       if (at != null) at = +at;
    847       if (at > this.length) at = this.length;
    848       if (at < 0) at += this.length + 1;
    849 
    850       var set = [];
    851       var toAdd = [];
    852       var toMerge = [];
    853       var toRemove = [];
    854       var modelMap = {};
    855 
    856       var add = options.add;
    857       var merge = options.merge;
    858       var remove = options.remove;
    859 
    860       var sort = false;
    861       var sortable = this.comparator && at == null && options.sort !== false;
    862       var sortAttr = _.isString(this.comparator) ? this.comparator : null;
    863 
    864       // Turn bare objects into model references, and prevent invalid models
    865       // from being added.
    866       var model, i;
    867       for (i = 0; i < models.length; i++) {
    868         model = models[i];
    869 
    870         // If a duplicate is found, prevent it from being added and
    871         // optionally merge it into the existing model.
    872         var existing = this.get(model);
    873         if (existing) {
    874           if (merge && model !== existing) {
    875             var attrs = this._isModel(model) ? model.attributes : model;
    876             if (options.parse) attrs = existing.parse(attrs, options);
    877             existing.set(attrs, options);
    878             toMerge.push(existing);
    879             if (sortable && !sort) sort = existing.hasChanged(sortAttr);
    880           }
    881           if (!modelMap[existing.cid]) {
    882             modelMap[existing.cid] = true;
    883             set.push(existing);
    884           }
    885           models[i] = existing;
    886 
    887         // If this is a new, valid model, push it to the `toAdd` list.
    888         } else if (add) {
    889           model = models[i] = this._prepareModel(model, options);
    890           if (model) {
    891             toAdd.push(model);
    892             this._addReference(model, options);
    893             modelMap[model.cid] = true;
    894             set.push(model);
    895           }
    896         }
    897       }
    898 
    899       // Remove stale models.
    900       if (remove) {
    901         for (i = 0; i < this.length; i++) {
    902           model = this.models[i];
    903           if (!modelMap[model.cid]) toRemove.push(model);
    904         }
    905         if (toRemove.length) this._removeModels(toRemove, options);
    906       }
    907 
    908       // See if sorting is needed, update `length` and splice in new models.
    909       var orderChanged = false;
    910       var replace = !sortable && add && remove;
    911       if (set.length && replace) {
    912         orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
    913           return m !== set[index];
    914         });
    915         this.models.length = 0;
    916         splice(this.models, set, 0);
    917         this.length = this.models.length;
    918       } else if (toAdd.length) {
    919         if (sortable) sort = true;
    920         splice(this.models, toAdd, at == null ? this.length : at);
    921         this.length = this.models.length;
    922       }
    923 
    924       // Silently sort the collection if appropriate.
    925       if (sort) this.sort({silent: true});
    926 
    927       // Unless silenced, it's time to fire all appropriate add/sort/update events.
    928       if (!options.silent) {
    929         for (i = 0; i < toAdd.length; i++) {
    930           if (at != null) options.index = at + i;
    931           model = toAdd[i];
    932           model.trigger('add', model, this, options);
    933         }
    934         if (sort || orderChanged) this.trigger('sort', this, options);
    935         if (toAdd.length || toRemove.length || toMerge.length) {
    936           options.changes = {
    937             added: toAdd,
    938             removed: toRemove,
    939             merged: toMerge
    940           };
    941           this.trigger('update', this, options);
    942         }
    943       }
    944 
    945       // Return the added (or merged) model (or models).
    946       return singular ? models[0] : models;
    947     },
    948 
    949     // When you have more items than you want to add or remove individually,
    950     // you can reset the entire set with a new list of models, without firing
    951     // any granular `add` or `remove` events. Fires `reset` when finished.
    952     // Useful for bulk operations and optimizations.
    953     reset: function(models, options) {
    954       options = options ? _.clone(options) : {};
    955       for (var i = 0; i < this.models.length; i++) {
    956         this._removeReference(this.models[i], options);
    957       }
    958       options.previousModels = this.models;
    959       this._reset();
    960       models = this.add(models, _.extend({silent: true}, options));
    961       if (!options.silent) this.trigger('reset', this, options);
    962       return models;
    963     },
    964 
    965     // Add a model to the end of the collection.
    966     push: function(model, options) {
    967       return this.add(model, _.extend({at: this.length}, options));
    968     },
    969 
    970     // Remove a model from the end of the collection.
    971     pop: function(options) {
    972       var model = this.at(this.length - 1);
    973       return this.remove(model, options);
    974     },
    975 
    976     // Add a model to the beginning of the collection.
    977     unshift: function(model, options) {
    978       return this.add(model, _.extend({at: 0}, options));
    979     },
    980 
    981     // Remove a model from the beginning of the collection.
    982     shift: function(options) {
    983       var model = this.at(0);
    984       return this.remove(model, options);
    985     },
    986 
    987     // Slice out a sub-array of models from the collection.
    988     slice: function() {
    989       return slice.apply(this.models, arguments);
    990     },
    991 
    992     // Get a model from the set by id, cid, model object with id or cid
    993     // properties, or an attributes object that is transformed through modelId.
    994     get: function(obj) {
    995       if (obj == null) return void 0;
    996       return this._byId[obj] ||
    997         this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj)] ||
    998         obj.cid && this._byId[obj.cid];
    999     },
   1000 
   1001     // Returns `true` if the model is in the collection.
   1002     has: function(obj) {
   1003       return this.get(obj) != null;
   1004     },
   1005 
   1006     // Get the model at the given index.
   1007     at: function(index) {
   1008       if (index < 0) index += this.length;
   1009       return this.models[index];
   1010     },
   1011 
   1012     // Return models with matching attributes. Useful for simple cases of
   1013     // `filter`.
   1014     where: function(attrs, first) {
   1015       return this[first ? 'find' : 'filter'](attrs);
   1016     },
   1017 
   1018     // Return the first model with matching attributes. Useful for simple cases
   1019     // of `find`.
   1020     findWhere: function(attrs) {
   1021       return this.where(attrs, true);
   1022     },
   1023 
   1024     // Force the collection to re-sort itself. You don't need to call this under
   1025     // normal circumstances, as the set will maintain sort order as each item
   1026     // is added.
   1027     sort: function(options) {
   1028       var comparator = this.comparator;
   1029       if (!comparator) throw new Error('Cannot sort a set without a comparator');
   1030       options || (options = {});
   1031 
   1032       var length = comparator.length;
   1033       if (_.isFunction(comparator)) comparator = comparator.bind(this);
   1034 
   1035       // Run sort based on type of `comparator`.
   1036       if (length === 1 || _.isString(comparator)) {
   1037         this.models = this.sortBy(comparator);
   1038       } else {
   1039         this.models.sort(comparator);
   1040       }
   1041       if (!options.silent) this.trigger('sort', this, options);
   1042       return this;
   1043     },
   1044 
   1045     // Pluck an attribute from each model in the collection.
   1046     pluck: function(attr) {
   1047       return this.map(attr + '');
   1048     },
   1049 
   1050     // Fetch the default set of models for this collection, resetting the
   1051     // collection when they arrive. If `reset: true` is passed, the response
   1052     // data will be passed through the `reset` method instead of `set`.
   1053     fetch: function(options) {
   1054       options = _.extend({parse: true}, options);
   1055       var success = options.success;
   1056       var collection = this;
   1057       options.success = function(resp) {
   1058         var method = options.reset ? 'reset' : 'set';
   1059         collection[method](resp, options);
   1060         if (success) success.call(options.context, collection, resp, options);
   1061         collection.trigger('sync', collection, resp, options);
   1062       };
   1063       wrapError(this, options);
   1064       return this.sync('read', this, options);
   1065     },
   1066 
   1067     // Create a new instance of a model in this collection. Add the model to the
   1068     // collection immediately, unless `wait: true` is passed, in which case we
   1069     // wait for the server to agree.
   1070     create: function(model, options) {
   1071       options = options ? _.clone(options) : {};
   1072       var wait = options.wait;
   1073       model = this._prepareModel(model, options);
   1074       if (!model) return false;
   1075       if (!wait) this.add(model, options);
   1076       var collection = this;
   1077       var success = options.success;
   1078       options.success = function(m, resp, callbackOpts) {
   1079         if (wait) collection.add(m, callbackOpts);
   1080         if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
   1081       };
   1082       model.save(null, options);
   1083       return model;
   1084     },
   1085 
   1086     // **parse** converts a response into a list of models to be added to the
   1087     // collection. The default implementation is just to pass it through.
   1088     parse: function(resp, options) {
   1089       return resp;
   1090     },
   1091 
   1092     // Create a new collection with an identical list of models as this one.
   1093     clone: function() {
   1094       return new this.constructor(this.models, {
   1095         model: this.model,
   1096         comparator: this.comparator
   1097       });
   1098     },
   1099 
   1100     // Define how to uniquely identify models in the collection.
   1101     modelId: function(attrs) {
   1102       return attrs[this.model.prototype.idAttribute || 'id'];
   1103     },
   1104 
   1105     // Get an iterator of all models in this collection.
   1106     values: function() {
   1107       return new CollectionIterator(this, ITERATOR_VALUES);
   1108     },
   1109 
   1110     // Get an iterator of all model IDs in this collection.
   1111     keys: function() {
   1112       return new CollectionIterator(this, ITERATOR_KEYS);
   1113     },
   1114 
   1115     // Get an iterator of all [ID, model] tuples in this collection.
   1116     entries: function() {
   1117       return new CollectionIterator(this, ITERATOR_KEYSVALUES);
   1118     },
   1119 
   1120     // Private method to reset all internal state. Called when the collection
   1121     // is first initialized or reset.
   1122     _reset: function() {
   1123       this.length = 0;
   1124       this.models = [];
   1125       this._byId  = {};
   1126     },
   1127 
   1128     // Prepare a hash of attributes (or other model) to be added to this
   1129     // collection.
   1130     _prepareModel: function(attrs, options) {
   1131       if (this._isModel(attrs)) {
   1132         if (!attrs.collection) attrs.collection = this;
   1133         return attrs;
   1134       }
   1135       options = options ? _.clone(options) : {};
   1136       options.collection = this;
   1137       var model = new this.model(attrs, options);
   1138       if (!model.validationError) return model;
   1139       this.trigger('invalid', this, model.validationError, options);
   1140       return false;
   1141     },
   1142 
   1143     // Internal method called by both remove and set.
   1144     _removeModels: function(models, options) {
   1145       var removed = [];
   1146       for (var i = 0; i < models.length; i++) {
   1147         var model = this.get(models[i]);
   1148         if (!model) continue;
   1149 
   1150         var index = this.indexOf(model);
   1151         this.models.splice(index, 1);
   1152         this.length--;
   1153 
   1154         // Remove references before triggering 'remove' event to prevent an
   1155         // infinite loop. #3693
   1156         delete this._byId[model.cid];
   1157         var id = this.modelId(model.attributes);
   1158         if (id != null) delete this._byId[id];
   1159 
   1160         if (!options.silent) {
   1161           options.index = index;
   1162           model.trigger('remove', model, this, options);
   1163         }
   1164 
   1165         removed.push(model);
   1166         this._removeReference(model, options);
   1167       }
   1168       return removed;
   1169     },
   1170 
   1171     // Method for checking whether an object should be considered a model for
   1172     // the purposes of adding to the collection.
   1173     _isModel: function(model) {
   1174       return model instanceof Model;
   1175     },
   1176 
   1177     // Internal method to create a model's ties to a collection.
   1178     _addReference: function(model, options) {
   1179       this._byId[model.cid] = model;
   1180       var id = this.modelId(model.attributes);
   1181       if (id != null) this._byId[id] = model;
   1182       model.on('all', this._onModelEvent, this);
   1183     },
   1184 
   1185     // Internal method to sever a model's ties to a collection.
   1186     _removeReference: function(model, options) {
   1187       delete this._byId[model.cid];
   1188       var id = this.modelId(model.attributes);
   1189       if (id != null) delete this._byId[id];
   1190       if (this === model.collection) delete model.collection;
   1191       model.off('all', this._onModelEvent, this);
   1192     },
   1193 
   1194     // Internal method called every time a model in the set fires an event.
   1195     // Sets need to update their indexes when models change ids. All other
   1196     // events simply proxy through. "add" and "remove" events that originate
   1197     // in other collections are ignored.
   1198     _onModelEvent: function(event, model, collection, options) {
   1199       if (model) {
   1200         if ((event === 'add' || event === 'remove') && collection !== this) return;
   1201         if (event === 'destroy') this.remove(model, options);
   1202         if (event === 'change') {
   1203           var prevId = this.modelId(model.previousAttributes());
   1204           var id = this.modelId(model.attributes);
   1205           if (prevId !== id) {
   1206             if (prevId != null) delete this._byId[prevId];
   1207             if (id != null) this._byId[id] = model;
   1208           }
   1209         }
   1210       }
   1211       this.trigger.apply(this, arguments);
   1212     }
   1213 
   1214   });
   1215 
   1216   // Defining an @@iterator method implements JavaScript's Iterable protocol.
   1217   // In modern ES2015 browsers, this value is found at Symbol.iterator.
   1218   /* global Symbol */
   1219   var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
   1220   if ($$iterator) {
   1221     Collection.prototype[$$iterator] = Collection.prototype.values;
   1222   }
   1223 
   1224   // CollectionIterator
   1225   // ------------------
   1226 
   1227   // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
   1228   // use of `for of` loops in modern browsers and interoperation between
   1229   // Backbone.Collection and other JavaScript functions and third-party libraries
   1230   // which can operate on Iterables.
   1231   var CollectionIterator = function(collection, kind) {
   1232     this._collection = collection;
   1233     this._kind = kind;
   1234     this._index = 0;
   1235   };
   1236 
   1237   // This "enum" defines the three possible kinds of values which can be emitted
   1238   // by a CollectionIterator that correspond to the values(), keys() and entries()
   1239   // methods on Collection, respectively.
   1240   var ITERATOR_VALUES = 1;
   1241   var ITERATOR_KEYS = 2;
   1242   var ITERATOR_KEYSVALUES = 3;
   1243 
   1244   // All Iterators should themselves be Iterable.
   1245   if ($$iterator) {
   1246     CollectionIterator.prototype[$$iterator] = function() {
   1247       return this;
   1248     };
   1249   }
   1250 
   1251   CollectionIterator.prototype.next = function() {
   1252     if (this._collection) {
   1253 
   1254       // Only continue iterating if the iterated collection is long enough.
   1255       if (this._index < this._collection.length) {
   1256         var model = this._collection.at(this._index);
   1257         this._index++;
   1258 
   1259         // Construct a value depending on what kind of values should be iterated.
   1260         var value;
   1261         if (this._kind === ITERATOR_VALUES) {
   1262           value = model;
   1263         } else {
   1264           var id = this._collection.modelId(model.attributes);
   1265           if (this._kind === ITERATOR_KEYS) {
   1266             value = id;
   1267           } else { // ITERATOR_KEYSVALUES
   1268             value = [id, model];
   1269           }
   1270         }
   1271         return {value: value, done: false};
   1272       }
   1273 
   1274       // Once exhausted, remove the reference to the collection so future
   1275       // calls to the next method always return done.
   1276       this._collection = void 0;
   1277     }
   1278 
   1279     return {value: void 0, done: true};
   1280   };
   1281 
   1282   // Backbone.View
   1283   // -------------
   1284 
   1285   // Backbone Views are almost more convention than they are actual code. A View
   1286   // is simply a JavaScript object that represents a logical chunk of UI in the
   1287   // DOM. This might be a single item, an entire list, a sidebar or panel, or
   1288   // even the surrounding frame which wraps your whole app. Defining a chunk of
   1289   // UI as a **View** allows you to define your DOM events declaratively, without
   1290   // having to worry about render order ... and makes it easy for the view to
   1291   // react to specific changes in the state of your models.
   1292 
   1293   // Creating a Backbone.View creates its initial element outside of the DOM,
   1294   // if an existing element is not provided...
   1295   var View = Backbone.View = function(options) {
   1296     this.cid = _.uniqueId('view');
   1297     this.preinitialize.apply(this, arguments);
   1298     _.extend(this, _.pick(options, viewOptions));
   1299     this._ensureElement();
   1300     this.initialize.apply(this, arguments);
   1301   };
   1302 
   1303   // Cached regex to split keys for `delegate`.
   1304   var delegateEventSplitter = /^(\S+)\s*(.*)$/;
   1305 
   1306   // List of view options to be set as properties.
   1307   var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
   1308 
   1309   // Set up all inheritable **Backbone.View** properties and methods.
   1310   _.extend(View.prototype, Events, {
   1311 
   1312     // The default `tagName` of a View's element is `"div"`.
   1313     tagName: 'div',
   1314 
   1315     // jQuery delegate for element lookup, scoped to DOM elements within the
   1316     // current view. This should be preferred to global lookups where possible.
   1317     $: function(selector) {
   1318       return this.$el.find(selector);
   1319     },
   1320 
   1321     // preinitialize is an empty function by default. You can override it with a function
   1322     // or object.  preinitialize will run before any instantiation logic is run in the View
   1323     preinitialize: function(){},
   1324 
   1325     // Initialize is an empty function by default. Override it with your own
   1326     // initialization logic.
   1327     initialize: function(){},
   1328 
   1329     // **render** is the core function that your view should override, in order
   1330     // to populate its element (`this.el`), with the appropriate HTML. The
   1331     // convention is for **render** to always return `this`.
   1332     render: function() {
   1333       return this;
   1334     },
   1335 
   1336     // Remove this view by taking the element out of the DOM, and removing any
   1337     // applicable Backbone.Events listeners.
   1338     remove: function() {
   1339       this._removeElement();
   1340       this.stopListening();
   1341       return this;
   1342     },
   1343 
   1344     // Remove this view's element from the document and all event listeners
   1345     // attached to it. Exposed for subclasses using an alternative DOM
   1346     // manipulation API.
   1347     _removeElement: function() {
   1348       this.$el.remove();
   1349     },
   1350 
   1351     // Change the view's element (`this.el` property) and re-delegate the
   1352     // view's events on the new element.
   1353     setElement: function(element) {
   1354       this.undelegateEvents();
   1355       this._setElement(element);
   1356       this.delegateEvents();
   1357       return this;
   1358     },
   1359 
   1360     // Creates the `this.el` and `this.$el` references for this view using the
   1361     // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
   1362     // context or an element. Subclasses can override this to utilize an
   1363     // alternative DOM manipulation API and are only required to set the
   1364     // `this.el` property.
   1365     _setElement: function(el) {
   1366       this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
   1367       this.el = this.$el[0];
   1368     },
   1369 
   1370     // Set callbacks, where `this.events` is a hash of
   1371     //
   1372     // *{"event selector": "callback"}*
   1373     //
   1374     //     {
   1375     //       'mousedown .title':  'edit',
   1376     //       'click .button':     'save',
   1377     //       'click .open':       function(e) { ... }
   1378     //     }
   1379     //
   1380     // pairs. Callbacks will be bound to the view, with `this` set properly.
   1381     // Uses event delegation for efficiency.
   1382     // Omitting the selector binds the event to `this.el`.
   1383     delegateEvents: function(events) {
   1384       events || (events = _.result(this, 'events'));
   1385       if (!events) return this;
   1386       this.undelegateEvents();
   1387       for (var key in events) {
   1388         var method = events[key];
   1389         if (!_.isFunction(method)) method = this[method];
   1390         if (!method) continue;
   1391         var match = key.match(delegateEventSplitter);
   1392         this.delegate(match[1], match[2], method.bind(this));
   1393       }
   1394       return this;
   1395     },
   1396 
   1397     // Add a single event listener to the view's element (or a child element
   1398     // using `selector`). This only works for delegate-able events: not `focus`,
   1399     // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
   1400     delegate: function(eventName, selector, listener) {
   1401       this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
   1402       return this;
   1403     },
   1404 
   1405     // Clears all callbacks previously bound to the view by `delegateEvents`.
   1406     // You usually don't need to use this, but may wish to if you have multiple
   1407     // Backbone views attached to the same DOM element.
   1408     undelegateEvents: function() {
   1409       if (this.$el) this.$el.off('.delegateEvents' + this.cid);
   1410       return this;
   1411     },
   1412 
   1413     // A finer-grained `undelegateEvents` for removing a single delegated event.
   1414     // `selector` and `listener` are both optional.
   1415     undelegate: function(eventName, selector, listener) {
   1416       this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
   1417       return this;
   1418     },
   1419 
   1420     // Produces a DOM element to be assigned to your view. Exposed for
   1421     // subclasses using an alternative DOM manipulation API.
   1422     _createElement: function(tagName) {
   1423       return document.createElement(tagName);
   1424     },
   1425 
   1426     // Ensure that the View has a DOM element to render into.
   1427     // If `this.el` is a string, pass it through `$()`, take the first
   1428     // matching element, and re-assign it to `el`. Otherwise, create
   1429     // an element from the `id`, `className` and `tagName` properties.
   1430     _ensureElement: function() {
   1431       if (!this.el) {
   1432         var attrs = _.extend({}, _.result(this, 'attributes'));
   1433         if (this.id) attrs.id = _.result(this, 'id');
   1434         if (this.className) attrs['class'] = _.result(this, 'className');
   1435         this.setElement(this._createElement(_.result(this, 'tagName')));
   1436         this._setAttributes(attrs);
   1437       } else {
   1438         this.setElement(_.result(this, 'el'));
   1439       }
   1440     },
   1441 
   1442     // Set attributes from a hash on this view's element.  Exposed for
   1443     // subclasses using an alternative DOM manipulation API.
   1444     _setAttributes: function(attributes) {
   1445       this.$el.attr(attributes);
   1446     }
   1447 
   1448   });
   1449 
   1450   // Proxy Backbone class methods to Underscore functions, wrapping the model's
   1451   // `attributes` object or collection's `models` array behind the scenes.
   1452   //
   1453   // collection.filter(function(model) { return model.get('age') > 10 });
   1454   // collection.each(this.addView);
   1455   //
   1456   // `Function#apply` can be slow so we use the method's arg count, if we know it.
   1457   var addMethod = function(base, length, method, attribute) {
   1458     switch (length) {
   1459       case 1: return function() {
   1460         return base[method](this[attribute]);
   1461       };
   1462       case 2: return function(value) {
   1463         return base[method](this[attribute], value);
   1464       };
   1465       case 3: return function(iteratee, context) {
   1466         return base[method](this[attribute], cb(iteratee, this), context);
   1467       };
   1468       case 4: return function(iteratee, defaultVal, context) {
   1469         return base[method](this[attribute], cb(iteratee, this), defaultVal, context);
   1470       };
   1471       default: return function() {
   1472         var args = slice.call(arguments);
   1473         args.unshift(this[attribute]);
   1474         return base[method].apply(base, args);
   1475       };
   1476     }
   1477   };
   1478 
   1479   var addUnderscoreMethods = function(Class, base, methods, attribute) {
   1480     _.each(methods, function(length, method) {
   1481       if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute);
   1482     });
   1483   };
   1484 
   1485   // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
   1486   var cb = function(iteratee, instance) {
   1487     if (_.isFunction(iteratee)) return iteratee;
   1488     if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
   1489     if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
   1490     return iteratee;
   1491   };
   1492   var modelMatcher = function(attrs) {
   1493     var matcher = _.matches(attrs);
   1494     return function(model) {
   1495       return matcher(model.attributes);
   1496     };
   1497   };
   1498 
   1499   // Underscore methods that we want to implement on the Collection.
   1500   // 90% of the core usefulness of Backbone Collections is actually implemented
   1501   // right here:
   1502   var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
   1503     foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
   1504     select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
   1505     contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
   1506     head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
   1507     without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
   1508     isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
   1509     sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};
   1510 
   1511 
   1512   // Underscore methods that we want to implement on the Model, mapped to the
   1513   // number of arguments they take.
   1514   var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
   1515     omit: 0, chain: 1, isEmpty: 1};
   1516 
   1517   // Mix in each Underscore method as a proxy to `Collection#models`.
   1518 
   1519   _.each([
   1520     [Collection, collectionMethods, 'models'],
   1521     [Model, modelMethods, 'attributes']
   1522   ], function(config) {
   1523     var Base = config[0],
   1524         methods = config[1],
   1525         attribute = config[2];
   1526 
   1527     Base.mixin = function(obj) {
   1528       var mappings = _.reduce(_.functions(obj), function(memo, name) {
   1529         memo[name] = 0;
   1530         return memo;
   1531       }, {});
   1532       addUnderscoreMethods(Base, obj, mappings, attribute);
   1533     };
   1534 
   1535     addUnderscoreMethods(Base, _, methods, attribute);
   1536   });
   1537 
   1538   // Backbone.sync
   1539   // -------------
   1540 
   1541   // Override this function to change the manner in which Backbone persists
   1542   // models to the server. You will be passed the type of request, and the
   1543   // model in question. By default, makes a RESTful Ajax request
   1544   // to the model's `url()`. Some possible customizations could be:
   1545   //
   1546   // * Use `setTimeout` to batch rapid-fire updates into a single request.
   1547   // * Send up the models as XML instead of JSON.
   1548   // * Persist models via WebSockets instead of Ajax.
   1549   //
   1550   // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
   1551   // as `POST`, with a `_method` parameter containing the true HTTP method,
   1552   // as well as all requests with the body as `application/x-www-form-urlencoded`
   1553   // instead of `application/json` with the model in a param named `model`.
   1554   // Useful when interfacing with server-side languages like **PHP** that make
   1555   // it difficult to read the body of `PUT` requests.
   1556   Backbone.sync = function(method, model, options) {
   1557     var type = methodMap[method];
   1558 
   1559     // Default options, unless specified.
   1560     _.defaults(options || (options = {}), {
   1561       emulateHTTP: Backbone.emulateHTTP,
   1562       emulateJSON: Backbone.emulateJSON
   1563     });
   1564 
   1565     // Default JSON-request options.
   1566     var params = {type: type, dataType: 'json'};
   1567 
   1568     // Ensure that we have a URL.
   1569     if (!options.url) {
   1570       params.url = _.result(model, 'url') || urlError();
   1571     }
   1572 
   1573     // Ensure that we have the appropriate request data.
   1574     if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
   1575       params.contentType = 'application/json';
   1576       params.data = JSON.stringify(options.attrs || model.toJSON(options));
   1577     }
   1578 
   1579     // For older servers, emulate JSON by encoding the request into an HTML-form.
   1580     if (options.emulateJSON) {
   1581       params.contentType = 'application/x-www-form-urlencoded';
   1582       params.data = params.data ? {model: params.data} : {};
   1583     }
   1584 
   1585     // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
   1586     // And an `X-HTTP-Method-Override` header.
   1587     if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
   1588       params.type = 'POST';
   1589       if (options.emulateJSON) params.data._method = type;
   1590       var beforeSend = options.beforeSend;
   1591       options.beforeSend = function(xhr) {
   1592         xhr.setRequestHeader('X-HTTP-Method-Override', type);
   1593         if (beforeSend) return beforeSend.apply(this, arguments);
   1594       };
   1595     }
   1596 
   1597     // Don't process data on a non-GET request.
   1598     if (params.type !== 'GET' && !options.emulateJSON) {
   1599       params.processData = false;
   1600     }
   1601 
   1602     // Pass along `textStatus` and `errorThrown` from jQuery.
   1603     var error = options.error;
   1604     options.error = function(xhr, textStatus, errorThrown) {
   1605       options.textStatus = textStatus;
   1606       options.errorThrown = errorThrown;
   1607       if (error) error.call(options.context, xhr, textStatus, errorThrown);
   1608     };
   1609 
   1610     // Make the request, allowing the user to override any Ajax options.
   1611     var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
   1612     model.trigger('request', model, xhr, options);
   1613     return xhr;
   1614   };
   1615 
   1616   // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
   1617   var methodMap = {
   1618     create: 'POST',
   1619     update: 'PUT',
   1620     patch: 'PATCH',
   1621     delete: 'DELETE',
   1622     read: 'GET'
   1623   };
   1624 
   1625   // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
   1626   // Override this if you'd like to use a different library.
   1627   Backbone.ajax = function() {
   1628     return Backbone.$.ajax.apply(Backbone.$, arguments);
   1629   };
   1630 
   1631   // Backbone.Router
   1632   // ---------------
   1633 
   1634   // Routers map faux-URLs to actions, and fire events when routes are
   1635   // matched. Creating a new one sets its `routes` hash, if not set statically.
   1636   var Router = Backbone.Router = function(options) {
   1637     options || (options = {});
   1638     this.preinitialize.apply(this, arguments);
   1639     if (options.routes) this.routes = options.routes;
   1640     this._bindRoutes();
   1641     this.initialize.apply(this, arguments);
   1642   };
   1643 
   1644   // Cached regular expressions for matching named param parts and splatted
   1645   // parts of route strings.
   1646   var optionalParam = /\((.*?)\)/g;
   1647   var namedParam    = /(\(\?)?:\w+/g;
   1648   var splatParam    = /\*\w+/g;
   1649   var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
   1650 
   1651   // Set up all inheritable **Backbone.Router** properties and methods.
   1652   _.extend(Router.prototype, Events, {
   1653 
   1654     // preinitialize is an empty function by default. You can override it with a function
   1655     // or object.  preinitialize will run before any instantiation logic is run in the Router.
   1656     preinitialize: function(){},
   1657 
   1658     // Initialize is an empty function by default. Override it with your own
   1659     // initialization logic.
   1660     initialize: function(){},
   1661 
   1662     // Manually bind a single named route to a callback. For example:
   1663     //
   1664     //     this.route('search/:query/p:num', 'search', function(query, num) {
   1665     //       ...
   1666     //     });
   1667     //
   1668     route: function(route, name, callback) {
   1669       if (!_.isRegExp(route)) route = this._routeToRegExp(route);
   1670       if (_.isFunction(name)) {
   1671         callback = name;
   1672         name = '';
   1673       }
   1674       if (!callback) callback = this[name];
   1675       var router = this;
   1676       Backbone.history.route(route, function(fragment) {
   1677         var args = router._extractParameters(route, fragment);
   1678         if (router.execute(callback, args, name) !== false) {
   1679           router.trigger.apply(router, ['route:' + name].concat(args));
   1680           router.trigger('route', name, args);
   1681           Backbone.history.trigger('route', router, name, args);
   1682         }
   1683       });
   1684       return this;
   1685     },
   1686 
   1687     // Execute a route handler with the provided parameters.  This is an
   1688     // excellent place to do pre-route setup or post-route cleanup.
   1689     execute: function(callback, args, name) {
   1690       if (callback) callback.apply(this, args);
   1691     },
   1692 
   1693     // Simple proxy to `Backbone.history` to save a fragment into the history.
   1694     navigate: function(fragment, options) {
   1695       Backbone.history.navigate(fragment, options);
   1696       return this;
   1697     },
   1698 
   1699     // Bind all defined routes to `Backbone.history`. We have to reverse the
   1700     // order of the routes here to support behavior where the most general
   1701     // routes can be defined at the bottom of the route map.
   1702     _bindRoutes: function() {
   1703       if (!this.routes) return;
   1704       this.routes = _.result(this, 'routes');
   1705       var route, routes = _.keys(this.routes);
   1706       while ((route = routes.pop()) != null) {
   1707         this.route(route, this.routes[route]);
   1708       }
   1709     },
   1710 
   1711     // Convert a route string into a regular expression, suitable for matching
   1712     // against the current location hash.
   1713     _routeToRegExp: function(route) {
   1714       route = route.replace(escapeRegExp, '\\$&')
   1715         .replace(optionalParam, '(?:$1)?')
   1716         .replace(namedParam, function(match, optional) {
   1717           return optional ? match : '([^/?]+)';
   1718         })
   1719         .replace(splatParam, '([^?]*?)');
   1720       return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
   1721     },
   1722 
   1723     // Given a route, and a URL fragment that it matches, return the array of
   1724     // extracted decoded parameters. Empty or unmatched parameters will be
   1725     // treated as `null` to normalize cross-browser behavior.
   1726     _extractParameters: function(route, fragment) {
   1727       var params = route.exec(fragment).slice(1);
   1728       return _.map(params, function(param, i) {
   1729         // Don't decode the search params.
   1730         if (i === params.length - 1) return param || null;
   1731         return param ? decodeURIComponent(param) : null;
   1732       });
   1733     }
   1734 
   1735   });
   1736 
   1737   // Backbone.History
   1738   // ----------------
   1739 
   1740   // Handles cross-browser history management, based on either
   1741   // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
   1742   // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
   1743   // and URL fragments. If the browser supports neither (old IE, natch),
   1744   // falls back to polling.
   1745   var History = Backbone.History = function() {
   1746     this.handlers = [];
   1747     this.checkUrl = this.checkUrl.bind(this);
   1748 
   1749     // Ensure that `History` can be used outside of the browser.
   1750     if (typeof window !== 'undefined') {
   1751       this.location = window.location;
   1752       this.history = window.history;
   1753     }
   1754   };
   1755 
   1756   // Cached regex for stripping a leading hash/slash and trailing space.
   1757   var routeStripper = /^[#\/]|\s+$/g;
   1758 
   1759   // Cached regex for stripping leading and trailing slashes.
   1760   var rootStripper = /^\/+|\/+$/g;
   1761 
   1762   // Cached regex for stripping urls of hash.
   1763   var pathStripper = /#.*$/;
   1764 
   1765   // Has the history handling already been started?
   1766   History.started = false;
   1767 
   1768   // Set up all inheritable **Backbone.History** properties and methods.
   1769   _.extend(History.prototype, Events, {
   1770 
   1771     // The default interval to poll for hash changes, if necessary, is
   1772     // twenty times a second.
   1773     interval: 50,
   1774 
   1775     // Are we at the app root?
   1776     atRoot: function() {
   1777       var path = this.location.pathname.replace(/[^\/]$/, '$&/');
   1778       return path === this.root && !this.getSearch();
   1779     },
   1780 
   1781     // Does the pathname match the root?
   1782     matchRoot: function() {
   1783       var path = this.decodeFragment(this.location.pathname);
   1784       var rootPath = path.slice(0, this.root.length - 1) + '/';
   1785       return rootPath === this.root;
   1786     },
   1787 
   1788     // Unicode characters in `location.pathname` are percent encoded so they're
   1789     // decoded for comparison. `%25` should not be decoded since it may be part
   1790     // of an encoded parameter.
   1791     decodeFragment: function(fragment) {
   1792       return decodeURI(fragment.replace(/%25/g, '%2525'));
   1793     },
   1794 
   1795     // In IE6, the hash fragment and search params are incorrect if the
   1796     // fragment contains `?`.
   1797     getSearch: function() {
   1798       var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
   1799       return match ? match[0] : '';
   1800     },
   1801 
   1802     // Gets the true hash value. Cannot use location.hash directly due to bug
   1803     // in Firefox where location.hash will always be decoded.
   1804     getHash: function(window) {
   1805       var match = (window || this).location.href.match(/#(.*)$/);
   1806       return match ? match[1] : '';
   1807     },
   1808 
   1809     // Get the pathname and search params, without the root.
   1810     getPath: function() {
   1811       var path = this.decodeFragment(
   1812         this.location.pathname + this.getSearch()
   1813       ).slice(this.root.length - 1);
   1814       return path.charAt(0) === '/' ? path.slice(1) : path;
   1815     },
   1816 
   1817     // Get the cross-browser normalized URL fragment from the path or hash.
   1818     getFragment: function(fragment) {
   1819       if (fragment == null) {
   1820         if (this._usePushState || !this._wantsHashChange) {
   1821           fragment = this.getPath();
   1822         } else {
   1823           fragment = this.getHash();
   1824         }
   1825       }
   1826       return fragment.replace(routeStripper, '');
   1827     },
   1828 
   1829     // Start the hash change handling, returning `true` if the current URL matches
   1830     // an existing route, and `false` otherwise.
   1831     start: function(options) {
   1832       if (History.started) throw new Error('Backbone.history has already been started');
   1833       History.started = true;
   1834 
   1835       // Figure out the initial configuration. Do we need an iframe?
   1836       // Is pushState desired ... is it available?
   1837       this.options          = _.extend({root: '/'}, this.options, options);
   1838       this.root             = this.options.root;
   1839       this._wantsHashChange = this.options.hashChange !== false;
   1840       this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
   1841       this._useHashChange   = this._wantsHashChange && this._hasHashChange;
   1842       this._wantsPushState  = !!this.options.pushState;
   1843       this._hasPushState    = !!(this.history && this.history.pushState);
   1844       this._usePushState    = this._wantsPushState && this._hasPushState;
   1845       this.fragment         = this.getFragment();
   1846 
   1847       // Normalize root to always include a leading and trailing slash.
   1848       this.root = ('/' + this.root + '/').replace(rootStripper, '/');
   1849 
   1850       // Transition from hashChange to pushState or vice versa if both are
   1851       // requested.
   1852       if (this._wantsHashChange && this._wantsPushState) {
   1853 
   1854         // If we've started off with a route from a `pushState`-enabled
   1855         // browser, but we're currently in a browser that doesn't support it...
   1856         if (!this._hasPushState && !this.atRoot()) {
   1857           var rootPath = this.root.slice(0, -1) || '/';
   1858           this.location.replace(rootPath + '#' + this.getPath());
   1859           // Return immediately as browser will do redirect to new url
   1860           return true;
   1861 
   1862         // Or if we've started out with a hash-based route, but we're currently
   1863         // in a browser where it could be `pushState`-based instead...
   1864         } else if (this._hasPushState && this.atRoot()) {
   1865           this.navigate(this.getHash(), {replace: true});
   1866         }
   1867 
   1868       }
   1869 
   1870       // Proxy an iframe to handle location events if the browser doesn't
   1871       // support the `hashchange` event, HTML5 history, or the user wants
   1872       // `hashChange` but not `pushState`.
   1873       if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
   1874         this.iframe = document.createElement('iframe');
   1875         this.iframe.src = 'javascript:0';
   1876         this.iframe.style.display = 'none';
   1877         this.iframe.tabIndex = -1;
   1878         var body = document.body;
   1879         // Using `appendChild` will throw on IE < 9 if the document is not ready.
   1880         var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
   1881         iWindow.document.open();
   1882         iWindow.document.close();
   1883         iWindow.location.hash = '#' + this.fragment;
   1884       }
   1885 
   1886       // Add a cross-platform `addEventListener` shim for older browsers.
   1887       var addEventListener = window.addEventListener || function(eventName, listener) {
   1888         return attachEvent('on' + eventName, listener);
   1889       };
   1890 
   1891       // Depending on whether we're using pushState or hashes, and whether
   1892       // 'onhashchange' is supported, determine how we check the URL state.
   1893       if (this._usePushState) {
   1894         addEventListener('popstate', this.checkUrl, false);
   1895       } else if (this._useHashChange && !this.iframe) {
   1896         addEventListener('hashchange', this.checkUrl, false);
   1897       } else if (this._wantsHashChange) {
   1898         this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
   1899       }
   1900 
   1901       if (!this.options.silent) return this.loadUrl();
   1902     },
   1903 
   1904     // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
   1905     // but possibly useful for unit testing Routers.
   1906     stop: function() {
   1907       // Add a cross-platform `removeEventListener` shim for older browsers.
   1908       var removeEventListener = window.removeEventListener || function(eventName, listener) {
   1909         return detachEvent('on' + eventName, listener);
   1910       };
   1911 
   1912       // Remove window listeners.
   1913       if (this._usePushState) {
   1914         removeEventListener('popstate', this.checkUrl, false);
   1915       } else if (this._useHashChange && !this.iframe) {
   1916         removeEventListener('hashchange', this.checkUrl, false);
   1917       }
   1918 
   1919       // Clean up the iframe if necessary.
   1920       if (this.iframe) {
   1921         document.body.removeChild(this.iframe);
   1922         this.iframe = null;
   1923       }
   1924 
   1925       // Some environments will throw when clearing an undefined interval.
   1926       if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
   1927       History.started = false;
   1928     },
   1929 
   1930     // Add a route to be tested when the fragment changes. Routes added later
   1931     // may override previous routes.
   1932     route: function(route, callback) {
   1933       this.handlers.unshift({route: route, callback: callback});
   1934     },
   1935 
   1936     // Checks the current URL to see if it has changed, and if it has,
   1937     // calls `loadUrl`, normalizing across the hidden iframe.
   1938     checkUrl: function(e) {
   1939       var current = this.getFragment();
   1940 
   1941       // If the user pressed the back button, the iframe's hash will have
   1942       // changed and we should use that for comparison.
   1943       if (current === this.fragment && this.iframe) {
   1944         current = this.getHash(this.iframe.contentWindow);
   1945       }
   1946 
   1947       if (current === this.fragment) return false;
   1948       if (this.iframe) this.navigate(current);
   1949       this.loadUrl();
   1950     },
   1951 
   1952     // Attempt to load the current URL fragment. If a route succeeds with a
   1953     // match, returns `true`. If no defined routes matches the fragment,
   1954     // returns `false`.
   1955     loadUrl: function(fragment) {
   1956       // If the root doesn't match, no routes can match either.
   1957       if (!this.matchRoot()) return false;
   1958       fragment = this.fragment = this.getFragment(fragment);
   1959       return _.some(this.handlers, function(handler) {
   1960         if (handler.route.test(fragment)) {
   1961           handler.callback(fragment);
   1962           return true;
   1963         }
   1964       });
   1965     },
   1966 
   1967     // Save a fragment into the hash history, or replace the URL state if the
   1968     // 'replace' option is passed. You are responsible for properly URL-encoding
   1969     // the fragment in advance.
   1970     //
   1971     // The options object can contain `trigger: true` if you wish to have the
   1972     // route callback be fired (not usually desirable), or `replace: true`, if
   1973     // you wish to modify the current URL without adding an entry to the history.
   1974     navigate: function(fragment, options) {
   1975       if (!History.started) return false;
   1976       if (!options || options === true) options = {trigger: !!options};
   1977 
   1978       // Normalize the fragment.
   1979       fragment = this.getFragment(fragment || '');
   1980 
   1981       // Don't include a trailing slash on the root.
   1982       var rootPath = this.root;
   1983       if (fragment === '' || fragment.charAt(0) === '?') {
   1984         rootPath = rootPath.slice(0, -1) || '/';
   1985       }
   1986       var url = rootPath + fragment;
   1987 
   1988       // Strip the fragment of the query and hash for matching.
   1989       fragment = fragment.replace(pathStripper, '');
   1990 
   1991       // Decode for matching.
   1992       var decodedFragment = this.decodeFragment(fragment);
   1993 
   1994       if (this.fragment === decodedFragment) return;
   1995       this.fragment = decodedFragment;
   1996 
   1997       // If pushState is available, we use it to set the fragment as a real URL.
   1998       if (this._usePushState) {
   1999         this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
   2000 
   2001       // If hash changes haven't been explicitly disabled, update the hash
   2002       // fragment to store history.
   2003       } else if (this._wantsHashChange) {
   2004         this._updateHash(this.location, fragment, options.replace);
   2005         if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
   2006           var iWindow = this.iframe.contentWindow;
   2007 
   2008           // Opening and closing the iframe tricks IE7 and earlier to push a
   2009           // history entry on hash-tag change.  When replace is true, we don't
   2010           // want this.
   2011           if (!options.replace) {
   2012             iWindow.document.open();
   2013             iWindow.document.close();
   2014           }
   2015 
   2016           this._updateHash(iWindow.location, fragment, options.replace);
   2017         }
   2018 
   2019       // If you've told us that you explicitly don't want fallback hashchange-
   2020       // based history, then `navigate` becomes a page refresh.
   2021       } else {
   2022         return this.location.assign(url);
   2023       }
   2024       if (options.trigger) return this.loadUrl(fragment);
   2025     },
   2026 
   2027     // Update the hash location, either replacing the current entry, or adding
   2028     // a new one to the browser history.
   2029     _updateHash: function(location, fragment, replace) {
   2030       if (replace) {
   2031         var href = location.href.replace(/(javascript:|#).*$/, '');
   2032         location.replace(href + '#' + fragment);
   2033       } else {
   2034         // Some browsers require that `hash` contains a leading #.
   2035         location.hash = '#' + fragment;
   2036       }
   2037     }
   2038 
   2039   });
   2040 
   2041   // Create the default Backbone.history.
   2042   Backbone.history = new History;
   2043 
   2044   // Helpers
   2045   // -------
   2046 
   2047   // Helper function to correctly set up the prototype chain for subclasses.
   2048   // Similar to `goog.inherits`, but uses a hash of prototype properties and
   2049   // class properties to be extended.
   2050   var extend = function(protoProps, staticProps) {
   2051     var parent = this;
   2052     var child;
   2053 
   2054     // The constructor function for the new subclass is either defined by you
   2055     // (the "constructor" property in your `extend` definition), or defaulted
   2056     // by us to simply call the parent constructor.
   2057     if (protoProps && _.has(protoProps, 'constructor')) {
   2058       child = protoProps.constructor;
   2059     } else {
   2060       child = function(){ return parent.apply(this, arguments); };
   2061     }
   2062 
   2063     // Add static properties to the constructor function, if supplied.
   2064     _.extend(child, parent, staticProps);
   2065 
   2066     // Set the prototype chain to inherit from `parent`, without calling
   2067     // `parent`'s constructor function and add the prototype properties.
   2068     child.prototype = _.create(parent.prototype, protoProps);
   2069     child.prototype.constructor = child;
   2070 
   2071     // Set a convenience property in case the parent's prototype is needed
   2072     // later.
   2073     child.__super__ = parent.prototype;
   2074 
   2075     return child;
   2076   };
   2077 
   2078   // Set up inheritance for the model, collection, router, view and history.
   2079   Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
   2080 
   2081   // Throw an error when a URL is needed, and none is supplied.
   2082   var urlError = function() {
   2083     throw new Error('A "url" property or function must be specified');
   2084   };
   2085 
   2086   // Wrap an optional error callback with a fallback error event.
   2087   var wrapError = function(model, options) {
   2088     var error = options.error;
   2089     options.error = function(resp) {
   2090       if (error) error.call(options.context, model, resp, options);
   2091       model.trigger('error', model, resp, options);
   2092     };
   2093   };
   2094 
   2095   return Backbone;
   2096 });