[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/js/ -> backbone.js (source)

   1  //     Backbone.js 1.4.1
   2  
   3  //     (c) 2010-2022 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.1';
  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) {
 520          var prevId = this.id;
 521          this.id = this.get(this.idAttribute);
 522          this.trigger('changeId', this, prevId, options);
 523        }
 524  
 525        // Trigger all relevant attribute changes.
 526        if (!silent) {
 527          if (changes.length) this._pending = options;
 528          for (var i = 0; i < changes.length; i++) {
 529            this.trigger('change:' + changes[i], this, current[changes[i]], options);
 530          }
 531        }
 532  
 533        // You might be wondering why there's a `while` loop here. Changes can
 534        // be recursively nested within `"change"` events.
 535        if (changing) return this;
 536        if (!silent) {
 537          while (this._pending) {
 538            options = this._pending;
 539            this._pending = false;
 540            this.trigger('change', this, options);
 541          }
 542        }
 543        this._pending = false;
 544        this._changing = false;
 545        return this;
 546      },
 547  
 548      // Remove an attribute from the model, firing `"change"`. `unset` is a noop
 549      // if the attribute doesn't exist.
 550      unset: function(attr, options) {
 551        return this.set(attr, void 0, _.extend({}, options, {unset: true}));
 552      },
 553  
 554      // Clear all attributes on the model, firing `"change"`.
 555      clear: function(options) {
 556        var attrs = {};
 557        for (var key in this.attributes) attrs[key] = void 0;
 558        return this.set(attrs, _.extend({}, options, {unset: true}));
 559      },
 560  
 561      // Determine if the model has changed since the last `"change"` event.
 562      // If you specify an attribute name, determine if that attribute has changed.
 563      hasChanged: function(attr) {
 564        if (attr == null) return !_.isEmpty(this.changed);
 565        return _.has(this.changed, attr);
 566      },
 567  
 568      // Return an object containing all the attributes that have changed, or
 569      // false if there are no changed attributes. Useful for determining what
 570      // parts of a view need to be updated and/or what attributes need to be
 571      // persisted to the server. Unset attributes will be set to undefined.
 572      // You can also pass an attributes object to diff against the model,
 573      // determining if there *would be* a change.
 574      changedAttributes: function(diff) {
 575        if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
 576        var old = this._changing ? this._previousAttributes : this.attributes;
 577        var changed = {};
 578        var hasChanged;
 579        for (var attr in diff) {
 580          var val = diff[attr];
 581          if (_.isEqual(old[attr], val)) continue;
 582          changed[attr] = val;
 583          hasChanged = true;
 584        }
 585        return hasChanged ? changed : false;
 586      },
 587  
 588      // Get the previous value of an attribute, recorded at the time the last
 589      // `"change"` event was fired.
 590      previous: function(attr) {
 591        if (attr == null || !this._previousAttributes) return null;
 592        return this._previousAttributes[attr];
 593      },
 594  
 595      // Get all of the attributes of the model at the time of the previous
 596      // `"change"` event.
 597      previousAttributes: function() {
 598        return _.clone(this._previousAttributes);
 599      },
 600  
 601      // Fetch the model from the server, merging the response with the model's
 602      // local attributes. Any changed attributes will trigger a "change" event.
 603      fetch: function(options) {
 604        options = _.extend({parse: true}, options);
 605        var model = this;
 606        var success = options.success;
 607        options.success = function(resp) {
 608          var serverAttrs = options.parse ? model.parse(resp, options) : resp;
 609          if (!model.set(serverAttrs, options)) return false;
 610          if (success) success.call(options.context, model, resp, options);
 611          model.trigger('sync', model, resp, options);
 612        };
 613        wrapError(this, options);
 614        return this.sync('read', this, options);
 615      },
 616  
 617      // Set a hash of model attributes, and sync the model to the server.
 618      // If the server returns an attributes hash that differs, the model's
 619      // state will be `set` again.
 620      save: function(key, val, options) {
 621        // Handle both `"key", value` and `{key: value}` -style arguments.
 622        var attrs;
 623        if (key == null || typeof key === 'object') {
 624          attrs = key;
 625          options = val;
 626        } else {
 627          (attrs = {})[key] = val;
 628        }
 629  
 630        options = _.extend({validate: true, parse: true}, options);
 631        var wait = options.wait;
 632  
 633        // If we're not waiting and attributes exist, save acts as
 634        // `set(attr).save(null, opts)` with validation. Otherwise, check if
 635        // the model will be valid when the attributes, if any, are set.
 636        if (attrs && !wait) {
 637          if (!this.set(attrs, options)) return false;
 638        } else if (!this._validate(attrs, options)) {
 639          return false;
 640        }
 641  
 642        // After a successful server-side save, the client is (optionally)
 643        // updated with the server-side state.
 644        var model = this;
 645        var success = options.success;
 646        var attributes = this.attributes;
 647        options.success = function(resp) {
 648          // Ensure attributes are restored during synchronous saves.
 649          model.attributes = attributes;
 650          var serverAttrs = options.parse ? model.parse(resp, options) : resp;
 651          if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
 652          if (serverAttrs && !model.set(serverAttrs, options)) return false;
 653          if (success) success.call(options.context, model, resp, options);
 654          model.trigger('sync', model, resp, options);
 655        };
 656        wrapError(this, options);
 657  
 658        // Set temporary attributes if `{wait: true}` to properly find new ids.
 659        if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
 660  
 661        var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
 662        if (method === 'patch' && !options.attrs) options.attrs = attrs;
 663        var xhr = this.sync(method, this, options);
 664  
 665        // Restore attributes.
 666        this.attributes = attributes;
 667  
 668        return xhr;
 669      },
 670  
 671      // Destroy this model on the server if it was already persisted.
 672      // Optimistically removes the model from its collection, if it has one.
 673      // If `wait: true` is passed, waits for the server to respond before removal.
 674      destroy: function(options) {
 675        options = options ? _.clone(options) : {};
 676        var model = this;
 677        var success = options.success;
 678        var wait = options.wait;
 679  
 680        var destroy = function() {
 681          model.stopListening();
 682          model.trigger('destroy', model, model.collection, options);
 683        };
 684  
 685        options.success = function(resp) {
 686          if (wait) destroy();
 687          if (success) success.call(options.context, model, resp, options);
 688          if (!model.isNew()) model.trigger('sync', model, resp, options);
 689        };
 690  
 691        var xhr = false;
 692        if (this.isNew()) {
 693          _.defer(options.success);
 694        } else {
 695          wrapError(this, options);
 696          xhr = this.sync('delete', this, options);
 697        }
 698        if (!wait) destroy();
 699        return xhr;
 700      },
 701  
 702      // Default URL for the model's representation on the server -- if you're
 703      // using Backbone's restful methods, override this to change the endpoint
 704      // that will be called.
 705      url: function() {
 706        var base =
 707          _.result(this, 'urlRoot') ||
 708          _.result(this.collection, 'url') ||
 709          urlError();
 710        if (this.isNew()) return base;
 711        var id = this.get(this.idAttribute);
 712        return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
 713      },
 714  
 715      // **parse** converts a response into the hash of attributes to be `set` on
 716      // the model. The default implementation is just to pass the response along.
 717      parse: function(resp, options) {
 718        return resp;
 719      },
 720  
 721      // Create a new model with identical attributes to this one.
 722      clone: function() {
 723        return new this.constructor(this.attributes);
 724      },
 725  
 726      // A model is new if it has never been saved to the server, and lacks an id.
 727      isNew: function() {
 728        return !this.has(this.idAttribute);
 729      },
 730  
 731      // Check if the model is currently in a valid state.
 732      isValid: function(options) {
 733        return this._validate({}, _.extend({}, options, {validate: true}));
 734      },
 735  
 736      // Run validation against the next complete set of model attributes,
 737      // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
 738      _validate: function(attrs, options) {
 739        if (!options.validate || !this.validate) return true;
 740        attrs = _.extend({}, this.attributes, attrs);
 741        var error = this.validationError = this.validate(attrs, options) || null;
 742        if (!error) return true;
 743        this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
 744        return false;
 745      }
 746  
 747    });
 748  
 749    // Backbone.Collection
 750    // -------------------
 751  
 752    // If models tend to represent a single row of data, a Backbone Collection is
 753    // more analogous to a table full of data ... or a small slice or page of that
 754    // table, or a collection of rows that belong together for a particular reason
 755    // -- all of the messages in this particular folder, all of the documents
 756    // belonging to this particular author, and so on. Collections maintain
 757    // indexes of their models, both in order, and for lookup by `id`.
 758  
 759    // Create a new **Collection**, perhaps to contain a specific type of `model`.
 760    // If a `comparator` is specified, the Collection will maintain
 761    // its models in sort order, as they're added and removed.
 762    var Collection = Backbone.Collection = function(models, options) {
 763      options || (options = {});
 764      this.preinitialize.apply(this, arguments);
 765      if (options.model) this.model = options.model;
 766      if (options.comparator !== void 0) this.comparator = options.comparator;
 767      this._reset();
 768      this.initialize.apply(this, arguments);
 769      if (models) this.reset(models, _.extend({silent: true}, options));
 770    };
 771  
 772    // Default options for `Collection#set`.
 773    var setOptions = {add: true, remove: true, merge: true};
 774    var addOptions = {add: true, remove: false};
 775  
 776    // Splices `insert` into `array` at index `at`.
 777    var splice = function(array, insert, at) {
 778      at = Math.min(Math.max(at, 0), array.length);
 779      var tail = Array(array.length - at);
 780      var length = insert.length;
 781      var i;
 782      for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
 783      for (i = 0; i < length; i++) array[i + at] = insert[i];
 784      for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
 785    };
 786  
 787    // Define the Collection's inheritable methods.
 788    _.extend(Collection.prototype, Events, {
 789  
 790      // The default model for a collection is just a **Backbone.Model**.
 791      // This should be overridden in most cases.
 792      model: Model,
 793  
 794  
 795      // preinitialize is an empty function by default. You can override it with a function
 796      // or object.  preinitialize will run before any instantiation logic is run in the Collection.
 797      preinitialize: function(){},
 798  
 799      // Initialize is an empty function by default. Override it with your own
 800      // initialization logic.
 801      initialize: function(){},
 802  
 803      // The JSON representation of a Collection is an array of the
 804      // models' attributes.
 805      toJSON: function(options) {
 806        return this.map(function(model) { return model.toJSON(options); });
 807      },
 808  
 809      // Proxy `Backbone.sync` by default.
 810      sync: function() {
 811        return Backbone.sync.apply(this, arguments);
 812      },
 813  
 814      // Add a model, or list of models to the set. `models` may be Backbone
 815      // Models or raw JavaScript objects to be converted to Models, or any
 816      // combination of the two.
 817      add: function(models, options) {
 818        return this.set(models, _.extend({merge: false}, options, addOptions));
 819      },
 820  
 821      // Remove a model, or a list of models from the set.
 822      remove: function(models, options) {
 823        options = _.extend({}, options);
 824        var singular = !_.isArray(models);
 825        models = singular ? [models] : models.slice();
 826        var removed = this._removeModels(models, options);
 827        if (!options.silent && removed.length) {
 828          options.changes = {added: [], merged: [], removed: removed};
 829          this.trigger('update', this, options);
 830        }
 831        return singular ? removed[0] : removed;
 832      },
 833  
 834      // Update a collection by `set`-ing a new list of models, adding new ones,
 835      // removing models that are no longer present, and merging models that
 836      // already exist in the collection, as necessary. Similar to **Model#set**,
 837      // the core operation for updating the data contained by the collection.
 838      set: function(models, options) {
 839        if (models == null) return;
 840  
 841        options = _.extend({}, setOptions, options);
 842        if (options.parse && !this._isModel(models)) {
 843          models = this.parse(models, options) || [];
 844        }
 845  
 846        var singular = !_.isArray(models);
 847        models = singular ? [models] : models.slice();
 848  
 849        var at = options.at;
 850        if (at != null) at = +at;
 851        if (at > this.length) at = this.length;
 852        if (at < 0) at += this.length + 1;
 853  
 854        var set = [];
 855        var toAdd = [];
 856        var toMerge = [];
 857        var toRemove = [];
 858        var modelMap = {};
 859  
 860        var add = options.add;
 861        var merge = options.merge;
 862        var remove = options.remove;
 863  
 864        var sort = false;
 865        var sortable = this.comparator && at == null && options.sort !== false;
 866        var sortAttr = _.isString(this.comparator) ? this.comparator : null;
 867  
 868        // Turn bare objects into model references, and prevent invalid models
 869        // from being added.
 870        var model, i;
 871        for (i = 0; i < models.length; i++) {
 872          model = models[i];
 873  
 874          // If a duplicate is found, prevent it from being added and
 875          // optionally merge it into the existing model.
 876          var existing = this.get(model);
 877          if (existing) {
 878            if (merge && model !== existing) {
 879              var attrs = this._isModel(model) ? model.attributes : model;
 880              if (options.parse) attrs = existing.parse(attrs, options);
 881              existing.set(attrs, options);
 882              toMerge.push(existing);
 883              if (sortable && !sort) sort = existing.hasChanged(sortAttr);
 884            }
 885            if (!modelMap[existing.cid]) {
 886              modelMap[existing.cid] = true;
 887              set.push(existing);
 888            }
 889            models[i] = existing;
 890  
 891          // If this is a new, valid model, push it to the `toAdd` list.
 892          } else if (add) {
 893            model = models[i] = this._prepareModel(model, options);
 894            if (model) {
 895              toAdd.push(model);
 896              this._addReference(model, options);
 897              modelMap[model.cid] = true;
 898              set.push(model);
 899            }
 900          }
 901        }
 902  
 903        // Remove stale models.
 904        if (remove) {
 905          for (i = 0; i < this.length; i++) {
 906            model = this.models[i];
 907            if (!modelMap[model.cid]) toRemove.push(model);
 908          }
 909          if (toRemove.length) this._removeModels(toRemove, options);
 910        }
 911  
 912        // See if sorting is needed, update `length` and splice in new models.
 913        var orderChanged = false;
 914        var replace = !sortable && add && remove;
 915        if (set.length && replace) {
 916          orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
 917            return m !== set[index];
 918          });
 919          this.models.length = 0;
 920          splice(this.models, set, 0);
 921          this.length = this.models.length;
 922        } else if (toAdd.length) {
 923          if (sortable) sort = true;
 924          splice(this.models, toAdd, at == null ? this.length : at);
 925          this.length = this.models.length;
 926        }
 927  
 928        // Silently sort the collection if appropriate.
 929        if (sort) this.sort({silent: true});
 930  
 931        // Unless silenced, it's time to fire all appropriate add/sort/update events.
 932        if (!options.silent) {
 933          for (i = 0; i < toAdd.length; i++) {
 934            if (at != null) options.index = at + i;
 935            model = toAdd[i];
 936            model.trigger('add', model, this, options);
 937          }
 938          if (sort || orderChanged) this.trigger('sort', this, options);
 939          if (toAdd.length || toRemove.length || toMerge.length) {
 940            options.changes = {
 941              added: toAdd,
 942              removed: toRemove,
 943              merged: toMerge
 944            };
 945            this.trigger('update', this, options);
 946          }
 947        }
 948  
 949        // Return the added (or merged) model (or models).
 950        return singular ? models[0] : models;
 951      },
 952  
 953      // When you have more items than you want to add or remove individually,
 954      // you can reset the entire set with a new list of models, without firing
 955      // any granular `add` or `remove` events. Fires `reset` when finished.
 956      // Useful for bulk operations and optimizations.
 957      reset: function(models, options) {
 958        options = options ? _.clone(options) : {};
 959        for (var i = 0; i < this.models.length; i++) {
 960          this._removeReference(this.models[i], options);
 961        }
 962        options.previousModels = this.models;
 963        this._reset();
 964        models = this.add(models, _.extend({silent: true}, options));
 965        if (!options.silent) this.trigger('reset', this, options);
 966        return models;
 967      },
 968  
 969      // Add a model to the end of the collection.
 970      push: function(model, options) {
 971        return this.add(model, _.extend({at: this.length}, options));
 972      },
 973  
 974      // Remove a model from the end of the collection.
 975      pop: function(options) {
 976        var model = this.at(this.length - 1);
 977        return this.remove(model, options);
 978      },
 979  
 980      // Add a model to the beginning of the collection.
 981      unshift: function(model, options) {
 982        return this.add(model, _.extend({at: 0}, options));
 983      },
 984  
 985      // Remove a model from the beginning of the collection.
 986      shift: function(options) {
 987        var model = this.at(0);
 988        return this.remove(model, options);
 989      },
 990  
 991      // Slice out a sub-array of models from the collection.
 992      slice: function() {
 993        return slice.apply(this.models, arguments);
 994      },
 995  
 996      // Get a model from the set by id, cid, model object with id or cid
 997      // properties, or an attributes object that is transformed through modelId.
 998      get: function(obj) {
 999        if (obj == null) return void 0;
1000        return this._byId[obj] ||
1001          this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj, obj.idAttribute)] ||
1002          obj.cid && this._byId[obj.cid];
1003      },
1004  
1005      // Returns `true` if the model is in the collection.
1006      has: function(obj) {
1007        return this.get(obj) != null;
1008      },
1009  
1010      // Get the model at the given index.
1011      at: function(index) {
1012        if (index < 0) index += this.length;
1013        return this.models[index];
1014      },
1015  
1016      // Return models with matching attributes. Useful for simple cases of
1017      // `filter`.
1018      where: function(attrs, first) {
1019        return this[first ? 'find' : 'filter'](attrs);
1020      },
1021  
1022      // Return the first model with matching attributes. Useful for simple cases
1023      // of `find`.
1024      findWhere: function(attrs) {
1025        return this.where(attrs, true);
1026      },
1027  
1028      // Force the collection to re-sort itself. You don't need to call this under
1029      // normal circumstances, as the set will maintain sort order as each item
1030      // is added.
1031      sort: function(options) {
1032        var comparator = this.comparator;
1033        if (!comparator) throw new Error('Cannot sort a set without a comparator');
1034        options || (options = {});
1035  
1036        var length = comparator.length;
1037        if (_.isFunction(comparator)) comparator = comparator.bind(this);
1038  
1039        // Run sort based on type of `comparator`.
1040        if (length === 1 || _.isString(comparator)) {
1041          this.models = this.sortBy(comparator);
1042        } else {
1043          this.models.sort(comparator);
1044        }
1045        if (!options.silent) this.trigger('sort', this, options);
1046        return this;
1047      },
1048  
1049      // Pluck an attribute from each model in the collection.
1050      pluck: function(attr) {
1051        return this.map(attr + '');
1052      },
1053  
1054      // Fetch the default set of models for this collection, resetting the
1055      // collection when they arrive. If `reset: true` is passed, the response
1056      // data will be passed through the `reset` method instead of `set`.
1057      fetch: function(options) {
1058        options = _.extend({parse: true}, options);
1059        var success = options.success;
1060        var collection = this;
1061        options.success = function(resp) {
1062          var method = options.reset ? 'reset' : 'set';
1063          collection[method](resp, options);
1064          if (success) success.call(options.context, collection, resp, options);
1065          collection.trigger('sync', collection, resp, options);
1066        };
1067        wrapError(this, options);
1068        return this.sync('read', this, options);
1069      },
1070  
1071      // Create a new instance of a model in this collection. Add the model to the
1072      // collection immediately, unless `wait: true` is passed, in which case we
1073      // wait for the server to agree.
1074      create: function(model, options) {
1075        options = options ? _.clone(options) : {};
1076        var wait = options.wait;
1077        model = this._prepareModel(model, options);
1078        if (!model) return false;
1079        if (!wait) this.add(model, options);
1080        var collection = this;
1081        var success = options.success;
1082        options.success = function(m, resp, callbackOpts) {
1083          if (wait) collection.add(m, callbackOpts);
1084          if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
1085        };
1086        model.save(null, options);
1087        return model;
1088      },
1089  
1090      // **parse** converts a response into a list of models to be added to the
1091      // collection. The default implementation is just to pass it through.
1092      parse: function(resp, options) {
1093        return resp;
1094      },
1095  
1096      // Create a new collection with an identical list of models as this one.
1097      clone: function() {
1098        return new this.constructor(this.models, {
1099          model: this.model,
1100          comparator: this.comparator
1101        });
1102      },
1103  
1104      // Define how to uniquely identify models in the collection.
1105      modelId: function(attrs, idAttribute) {
1106        return attrs[idAttribute || this.model.prototype.idAttribute || 'id'];
1107      },
1108  
1109      // Get an iterator of all models in this collection.
1110      values: function() {
1111        return new CollectionIterator(this, ITERATOR_VALUES);
1112      },
1113  
1114      // Get an iterator of all model IDs in this collection.
1115      keys: function() {
1116        return new CollectionIterator(this, ITERATOR_KEYS);
1117      },
1118  
1119      // Get an iterator of all [ID, model] tuples in this collection.
1120      entries: function() {
1121        return new CollectionIterator(this, ITERATOR_KEYSVALUES);
1122      },
1123  
1124      // Private method to reset all internal state. Called when the collection
1125      // is first initialized or reset.
1126      _reset: function() {
1127        this.length = 0;
1128        this.models = [];
1129        this._byId  = {};
1130      },
1131  
1132      // Prepare a hash of attributes (or other model) to be added to this
1133      // collection.
1134      _prepareModel: function(attrs, options) {
1135        if (this._isModel(attrs)) {
1136          if (!attrs.collection) attrs.collection = this;
1137          return attrs;
1138        }
1139        options = options ? _.clone(options) : {};
1140        options.collection = this;
1141  
1142        var model;
1143        if (this.model.prototype) {
1144          model = new this.model(attrs, options);
1145        } else {
1146          // ES class methods didn't have prototype
1147          model = this.model(attrs, options);
1148        }
1149  
1150        if (!model.validationError) return model;
1151        this.trigger('invalid', this, model.validationError, options);
1152        return false;
1153      },
1154  
1155      // Internal method called by both remove and set.
1156      _removeModels: function(models, options) {
1157        var removed = [];
1158        for (var i = 0; i < models.length; i++) {
1159          var model = this.get(models[i]);
1160          if (!model) continue;
1161  
1162          var index = this.indexOf(model);
1163          this.models.splice(index, 1);
1164          this.length--;
1165  
1166          // Remove references before triggering 'remove' event to prevent an
1167          // infinite loop. #3693
1168          delete this._byId[model.cid];
1169          var id = this.modelId(model.attributes, model.idAttribute);
1170          if (id != null) delete this._byId[id];
1171  
1172          if (!options.silent) {
1173            options.index = index;
1174            model.trigger('remove', model, this, options);
1175          }
1176  
1177          removed.push(model);
1178          this._removeReference(model, options);
1179        }
1180        return removed;
1181      },
1182  
1183      // Method for checking whether an object should be considered a model for
1184      // the purposes of adding to the collection.
1185      _isModel: function(model) {
1186        return model instanceof Model;
1187      },
1188  
1189      // Internal method to create a model's ties to a collection.
1190      _addReference: function(model, options) {
1191        this._byId[model.cid] = model;
1192        var id = this.modelId(model.attributes, model.idAttribute);
1193        if (id != null) this._byId[id] = model;
1194        model.on('all', this._onModelEvent, this);
1195      },
1196  
1197      // Internal method to sever a model's ties to a collection.
1198      _removeReference: function(model, options) {
1199        delete this._byId[model.cid];
1200        var id = this.modelId(model.attributes, model.idAttribute);
1201        if (id != null) delete this._byId[id];
1202        if (this === model.collection) delete model.collection;
1203        model.off('all', this._onModelEvent, this);
1204      },
1205  
1206      // Internal method called every time a model in the set fires an event.
1207      // Sets need to update their indexes when models change ids. All other
1208      // events simply proxy through. "add" and "remove" events that originate
1209      // in other collections are ignored.
1210      _onModelEvent: function(event, model, collection, options) {
1211        if (model) {
1212          if ((event === 'add' || event === 'remove') && collection !== this) return;
1213          if (event === 'destroy') this.remove(model, options);
1214          if (event === 'changeId') {
1215            var prevId = this.modelId(model.previousAttributes(), model.idAttribute);
1216            var id = this.modelId(model.attributes, model.idAttribute);
1217            if (prevId != null) delete this._byId[prevId];
1218            if (id != null) this._byId[id] = model;
1219          }
1220        }
1221        this.trigger.apply(this, arguments);
1222      }
1223  
1224    });
1225  
1226    // Defining an @@iterator method implements JavaScript's Iterable protocol.
1227    // In modern ES2015 browsers, this value is found at Symbol.iterator.
1228    /* global Symbol */
1229    var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
1230    if ($$iterator) {
1231      Collection.prototype[$$iterator] = Collection.prototype.values;
1232    }
1233  
1234    // CollectionIterator
1235    // ------------------
1236  
1237    // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
1238    // use of `for of` loops in modern browsers and interoperation between
1239    // Backbone.Collection and other JavaScript functions and third-party libraries
1240    // which can operate on Iterables.
1241    var CollectionIterator = function(collection, kind) {
1242      this._collection = collection;
1243      this._kind = kind;
1244      this._index = 0;
1245    };
1246  
1247    // This "enum" defines the three possible kinds of values which can be emitted
1248    // by a CollectionIterator that correspond to the values(), keys() and entries()
1249    // methods on Collection, respectively.
1250    var ITERATOR_VALUES = 1;
1251    var ITERATOR_KEYS = 2;
1252    var ITERATOR_KEYSVALUES = 3;
1253  
1254    // All Iterators should themselves be Iterable.
1255    if ($$iterator) {
1256      CollectionIterator.prototype[$$iterator] = function() {
1257        return this;
1258      };
1259    }
1260  
1261    CollectionIterator.prototype.next = function() {
1262      if (this._collection) {
1263  
1264        // Only continue iterating if the iterated collection is long enough.
1265        if (this._index < this._collection.length) {
1266          var model = this._collection.at(this._index);
1267          this._index++;
1268  
1269          // Construct a value depending on what kind of values should be iterated.
1270          var value;
1271          if (this._kind === ITERATOR_VALUES) {
1272            value = model;
1273          } else {
1274            var id = this._collection.modelId(model.attributes, model.idAttribute);
1275            if (this._kind === ITERATOR_KEYS) {
1276              value = id;
1277            } else { // ITERATOR_KEYSVALUES
1278              value = [id, model];
1279            }
1280          }
1281          return {value: value, done: false};
1282        }
1283  
1284        // Once exhausted, remove the reference to the collection so future
1285        // calls to the next method always return done.
1286        this._collection = void 0;
1287      }
1288  
1289      return {value: void 0, done: true};
1290    };
1291  
1292    // Backbone.View
1293    // -------------
1294  
1295    // Backbone Views are almost more convention than they are actual code. A View
1296    // is simply a JavaScript object that represents a logical chunk of UI in the
1297    // DOM. This might be a single item, an entire list, a sidebar or panel, or
1298    // even the surrounding frame which wraps your whole app. Defining a chunk of
1299    // UI as a **View** allows you to define your DOM events declaratively, without
1300    // having to worry about render order ... and makes it easy for the view to
1301    // react to specific changes in the state of your models.
1302  
1303    // Creating a Backbone.View creates its initial element outside of the DOM,
1304    // if an existing element is not provided...
1305    var View = Backbone.View = function(options) {
1306      this.cid = _.uniqueId('view');
1307      this.preinitialize.apply(this, arguments);
1308      _.extend(this, _.pick(options, viewOptions));
1309      this._ensureElement();
1310      this.initialize.apply(this, arguments);
1311    };
1312  
1313    // Cached regex to split keys for `delegate`.
1314    var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1315  
1316    // List of view options to be set as properties.
1317    var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1318  
1319    // Set up all inheritable **Backbone.View** properties and methods.
1320    _.extend(View.prototype, Events, {
1321  
1322      // The default `tagName` of a View's element is `"div"`.
1323      tagName: 'div',
1324  
1325      // jQuery delegate for element lookup, scoped to DOM elements within the
1326      // current view. This should be preferred to global lookups where possible.
1327      $: function(selector) {
1328        return this.$el.find(selector);
1329      },
1330  
1331      // preinitialize is an empty function by default. You can override it with a function
1332      // or object.  preinitialize will run before any instantiation logic is run in the View
1333      preinitialize: function(){},
1334  
1335      // Initialize is an empty function by default. Override it with your own
1336      // initialization logic.
1337      initialize: function(){},
1338  
1339      // **render** is the core function that your view should override, in order
1340      // to populate its element (`this.el`), with the appropriate HTML. The
1341      // convention is for **render** to always return `this`.
1342      render: function() {
1343        return this;
1344      },
1345  
1346      // Remove this view by taking the element out of the DOM, and removing any
1347      // applicable Backbone.Events listeners.
1348      remove: function() {
1349        this._removeElement();
1350        this.stopListening();
1351        return this;
1352      },
1353  
1354      // Remove this view's element from the document and all event listeners
1355      // attached to it. Exposed for subclasses using an alternative DOM
1356      // manipulation API.
1357      _removeElement: function() {
1358        this.$el.remove();
1359      },
1360  
1361      // Change the view's element (`this.el` property) and re-delegate the
1362      // view's events on the new element.
1363      setElement: function(element) {
1364        this.undelegateEvents();
1365        this._setElement(element);
1366        this.delegateEvents();
1367        return this;
1368      },
1369  
1370      // Creates the `this.el` and `this.$el` references for this view using the
1371      // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
1372      // context or an element. Subclasses can override this to utilize an
1373      // alternative DOM manipulation API and are only required to set the
1374      // `this.el` property.
1375      _setElement: function(el) {
1376        this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
1377        this.el = this.$el[0];
1378      },
1379  
1380      // Set callbacks, where `this.events` is a hash of
1381      //
1382      // *{"event selector": "callback"}*
1383      //
1384      //     {
1385      //       'mousedown .title':  'edit',
1386      //       'click .button':     'save',
1387      //       'click .open':       function(e) { ... }
1388      //     }
1389      //
1390      // pairs. Callbacks will be bound to the view, with `this` set properly.
1391      // Uses event delegation for efficiency.
1392      // Omitting the selector binds the event to `this.el`.
1393      delegateEvents: function(events) {
1394        events || (events = _.result(this, 'events'));
1395        if (!events) return this;
1396        this.undelegateEvents();
1397        for (var key in events) {
1398          var method = events[key];
1399          if (!_.isFunction(method)) method = this[method];
1400          if (!method) continue;
1401          var match = key.match(delegateEventSplitter);
1402          this.delegate(match[1], match[2], method.bind(this));
1403        }
1404        return this;
1405      },
1406  
1407      // Add a single event listener to the view's element (or a child element
1408      // using `selector`). This only works for delegate-able events: not `focus`,
1409      // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
1410      delegate: function(eventName, selector, listener) {
1411        this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
1412        return this;
1413      },
1414  
1415      // Clears all callbacks previously bound to the view by `delegateEvents`.
1416      // You usually don't need to use this, but may wish to if you have multiple
1417      // Backbone views attached to the same DOM element.
1418      undelegateEvents: function() {
1419        if (this.$el) this.$el.off('.delegateEvents' + this.cid);
1420        return this;
1421      },
1422  
1423      // A finer-grained `undelegateEvents` for removing a single delegated event.
1424      // `selector` and `listener` are both optional.
1425      undelegate: function(eventName, selector, listener) {
1426        this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
1427        return this;
1428      },
1429  
1430      // Produces a DOM element to be assigned to your view. Exposed for
1431      // subclasses using an alternative DOM manipulation API.
1432      _createElement: function(tagName) {
1433        return document.createElement(tagName);
1434      },
1435  
1436      // Ensure that the View has a DOM element to render into.
1437      // If `this.el` is a string, pass it through `$()`, take the first
1438      // matching element, and re-assign it to `el`. Otherwise, create
1439      // an element from the `id`, `className` and `tagName` properties.
1440      _ensureElement: function() {
1441        if (!this.el) {
1442          var attrs = _.extend({}, _.result(this, 'attributes'));
1443          if (this.id) attrs.id = _.result(this, 'id');
1444          if (this.className) attrs['class'] = _.result(this, 'className');
1445          this.setElement(this._createElement(_.result(this, 'tagName')));
1446          this._setAttributes(attrs);
1447        } else {
1448          this.setElement(_.result(this, 'el'));
1449        }
1450      },
1451  
1452      // Set attributes from a hash on this view's element.  Exposed for
1453      // subclasses using an alternative DOM manipulation API.
1454      _setAttributes: function(attributes) {
1455        this.$el.attr(attributes);
1456      }
1457  
1458    });
1459  
1460    // Proxy Backbone class methods to Underscore functions, wrapping the model's
1461    // `attributes` object or collection's `models` array behind the scenes.
1462    //
1463    // collection.filter(function(model) { return model.get('age') > 10 });
1464    // collection.each(this.addView);
1465    //
1466    // `Function#apply` can be slow so we use the method's arg count, if we know it.
1467    var addMethod = function(base, length, method, attribute) {
1468      switch (length) {
1469        case 1: return function() {
1470          return base[method](this[attribute]);
1471        };
1472        case 2: return function(value) {
1473          return base[method](this[attribute], value);
1474        };
1475        case 3: return function(iteratee, context) {
1476          return base[method](this[attribute], cb(iteratee, this), context);
1477        };
1478        case 4: return function(iteratee, defaultVal, context) {
1479          return base[method](this[attribute], cb(iteratee, this), defaultVal, context);
1480        };
1481        default: return function() {
1482          var args = slice.call(arguments);
1483          args.unshift(this[attribute]);
1484          return base[method].apply(base, args);
1485        };
1486      }
1487    };
1488  
1489    var addUnderscoreMethods = function(Class, base, methods, attribute) {
1490      _.each(methods, function(length, method) {
1491        if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute);
1492      });
1493    };
1494  
1495    // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
1496    var cb = function(iteratee, instance) {
1497      if (_.isFunction(iteratee)) return iteratee;
1498      if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
1499      if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
1500      return iteratee;
1501    };
1502    var modelMatcher = function(attrs) {
1503      var matcher = _.matches(attrs);
1504      return function(model) {
1505        return matcher(model.attributes);
1506      };
1507    };
1508  
1509    // Underscore methods that we want to implement on the Collection.
1510    // 90% of the core usefulness of Backbone Collections is actually implemented
1511    // right here:
1512    var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
1513      foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
1514      select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
1515      contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
1516      head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
1517      without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
1518      isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
1519      sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};
1520  
1521  
1522    // Underscore methods that we want to implement on the Model, mapped to the
1523    // number of arguments they take.
1524    var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
1525      omit: 0, chain: 1, isEmpty: 1};
1526  
1527    // Mix in each Underscore method as a proxy to `Collection#models`.
1528  
1529    _.each([
1530      [Collection, collectionMethods, 'models'],
1531      [Model, modelMethods, 'attributes']
1532    ], function(config) {
1533      var Base = config[0],
1534          methods = config[1],
1535          attribute = config[2];
1536  
1537      Base.mixin = function(obj) {
1538        var mappings = _.reduce(_.functions(obj), function(memo, name) {
1539          memo[name] = 0;
1540          return memo;
1541        }, {});
1542        addUnderscoreMethods(Base, obj, mappings, attribute);
1543      };
1544  
1545      addUnderscoreMethods(Base, _, methods, attribute);
1546    });
1547  
1548    // Backbone.sync
1549    // -------------
1550  
1551    // Override this function to change the manner in which Backbone persists
1552    // models to the server. You will be passed the type of request, and the
1553    // model in question. By default, makes a RESTful Ajax request
1554    // to the model's `url()`. Some possible customizations could be:
1555    //
1556    // * Use `setTimeout` to batch rapid-fire updates into a single request.
1557    // * Send up the models as XML instead of JSON.
1558    // * Persist models via WebSockets instead of Ajax.
1559    //
1560    // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1561    // as `POST`, with a `_method` parameter containing the true HTTP method,
1562    // as well as all requests with the body as `application/x-www-form-urlencoded`
1563    // instead of `application/json` with the model in a param named `model`.
1564    // Useful when interfacing with server-side languages like **PHP** that make
1565    // it difficult to read the body of `PUT` requests.
1566    Backbone.sync = function(method, model, options) {
1567      var type = methodMap[method];
1568  
1569      // Default options, unless specified.
1570      _.defaults(options || (options = {}), {
1571        emulateHTTP: Backbone.emulateHTTP,
1572        emulateJSON: Backbone.emulateJSON
1573      });
1574  
1575      // Default JSON-request options.
1576      var params = {type: type, dataType: 'json'};
1577  
1578      // Ensure that we have a URL.
1579      if (!options.url) {
1580        params.url = _.result(model, 'url') || urlError();
1581      }
1582  
1583      // Ensure that we have the appropriate request data.
1584      if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1585        params.contentType = 'application/json';
1586        params.data = JSON.stringify(options.attrs || model.toJSON(options));
1587      }
1588  
1589      // For older servers, emulate JSON by encoding the request into an HTML-form.
1590      if (options.emulateJSON) {
1591        params.contentType = 'application/x-www-form-urlencoded';
1592        params.data = params.data ? {model: params.data} : {};
1593      }
1594  
1595      // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1596      // And an `X-HTTP-Method-Override` header.
1597      if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1598        params.type = 'POST';
1599        if (options.emulateJSON) params.data._method = type;
1600        var beforeSend = options.beforeSend;
1601        options.beforeSend = function(xhr) {
1602          xhr.setRequestHeader('X-HTTP-Method-Override', type);
1603          if (beforeSend) return beforeSend.apply(this, arguments);
1604        };
1605      }
1606  
1607      // Don't process data on a non-GET request.
1608      if (params.type !== 'GET' && !options.emulateJSON) {
1609        params.processData = false;
1610      }
1611  
1612      // Pass along `textStatus` and `errorThrown` from jQuery.
1613      var error = options.error;
1614      options.error = function(xhr, textStatus, errorThrown) {
1615        options.textStatus = textStatus;
1616        options.errorThrown = errorThrown;
1617        if (error) error.call(options.context, xhr, textStatus, errorThrown);
1618      };
1619  
1620      // Make the request, allowing the user to override any Ajax options.
1621      var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1622      model.trigger('request', model, xhr, options);
1623      return xhr;
1624    };
1625  
1626    // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1627    var methodMap = {
1628      'create': 'POST',
1629      'update': 'PUT',
1630      'patch': 'PATCH',
1631      'delete': 'DELETE',
1632      'read': 'GET'
1633    };
1634  
1635    // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1636    // Override this if you'd like to use a different library.
1637    Backbone.ajax = function() {
1638      return Backbone.$.ajax.apply(Backbone.$, arguments);
1639    };
1640  
1641    // Backbone.Router
1642    // ---------------
1643  
1644    // Routers map faux-URLs to actions, and fire events when routes are
1645    // matched. Creating a new one sets its `routes` hash, if not set statically.
1646    var Router = Backbone.Router = function(options) {
1647      options || (options = {});
1648      this.preinitialize.apply(this, arguments);
1649      if (options.routes) this.routes = options.routes;
1650      this._bindRoutes();
1651      this.initialize.apply(this, arguments);
1652    };
1653  
1654    // Cached regular expressions for matching named param parts and splatted
1655    // parts of route strings.
1656    var optionalParam = /\((.*?)\)/g;
1657    var namedParam    = /(\(\?)?:\w+/g;
1658    var splatParam    = /\*\w+/g;
1659    var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1660  
1661    // Set up all inheritable **Backbone.Router** properties and methods.
1662    _.extend(Router.prototype, Events, {
1663  
1664      // preinitialize is an empty function by default. You can override it with a function
1665      // or object.  preinitialize will run before any instantiation logic is run in the Router.
1666      preinitialize: function(){},
1667  
1668      // Initialize is an empty function by default. Override it with your own
1669      // initialization logic.
1670      initialize: function(){},
1671  
1672      // Manually bind a single named route to a callback. For example:
1673      //
1674      //     this.route('search/:query/p:num', 'search', function(query, num) {
1675      //       ...
1676      //     });
1677      //
1678      route: function(route, name, callback) {
1679        if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1680        if (_.isFunction(name)) {
1681          callback = name;
1682          name = '';
1683        }
1684        if (!callback) callback = this[name];
1685        var router = this;
1686        Backbone.history.route(route, function(fragment) {
1687          var args = router._extractParameters(route, fragment);
1688          if (router.execute(callback, args, name) !== false) {
1689            router.trigger.apply(router, ['route:' + name].concat(args));
1690            router.trigger('route', name, args);
1691            Backbone.history.trigger('route', router, name, args);
1692          }
1693        });
1694        return this;
1695      },
1696  
1697      // Execute a route handler with the provided parameters.  This is an
1698      // excellent place to do pre-route setup or post-route cleanup.
1699      execute: function(callback, args, name) {
1700        if (callback) callback.apply(this, args);
1701      },
1702  
1703      // Simple proxy to `Backbone.history` to save a fragment into the history.
1704      navigate: function(fragment, options) {
1705        Backbone.history.navigate(fragment, options);
1706        return this;
1707      },
1708  
1709      // Bind all defined routes to `Backbone.history`. We have to reverse the
1710      // order of the routes here to support behavior where the most general
1711      // routes can be defined at the bottom of the route map.
1712      _bindRoutes: function() {
1713        if (!this.routes) return;
1714        this.routes = _.result(this, 'routes');
1715        var route, routes = _.keys(this.routes);
1716        while ((route = routes.pop()) != null) {
1717          this.route(route, this.routes[route]);
1718        }
1719      },
1720  
1721      // Convert a route string into a regular expression, suitable for matching
1722      // against the current location hash.
1723      _routeToRegExp: function(route) {
1724        route = route.replace(escapeRegExp, '\\$&')
1725        .replace(optionalParam, '(?:$1)?')
1726        .replace(namedParam, function(match, optional) {
1727          return optional ? match : '([^/?]+)';
1728        })
1729        .replace(splatParam, '([^?]*?)');
1730        return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
1731      },
1732  
1733      // Given a route, and a URL fragment that it matches, return the array of
1734      // extracted decoded parameters. Empty or unmatched parameters will be
1735      // treated as `null` to normalize cross-browser behavior.
1736      _extractParameters: function(route, fragment) {
1737        var params = route.exec(fragment).slice(1);
1738        return _.map(params, function(param, i) {
1739          // Don't decode the search params.
1740          if (i === params.length - 1) return param || null;
1741          return param ? decodeURIComponent(param) : null;
1742        });
1743      }
1744  
1745    });
1746  
1747    // Backbone.History
1748    // ----------------
1749  
1750    // Handles cross-browser history management, based on either
1751    // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1752    // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1753    // and URL fragments. If the browser supports neither (old IE, natch),
1754    // falls back to polling.
1755    var History = Backbone.History = function() {
1756      this.handlers = [];
1757      this.checkUrl = this.checkUrl.bind(this);
1758  
1759      // Ensure that `History` can be used outside of the browser.
1760      if (typeof window !== 'undefined') {
1761        this.location = window.location;
1762        this.history = window.history;
1763      }
1764    };
1765  
1766    // Cached regex for stripping a leading hash/slash and trailing space.
1767    var routeStripper = /^[#\/]|\s+$/g;
1768  
1769    // Cached regex for stripping leading and trailing slashes.
1770    var rootStripper = /^\/+|\/+$/g;
1771  
1772    // Cached regex for stripping urls of hash.
1773    var pathStripper = /#.*$/;
1774  
1775    // Has the history handling already been started?
1776    History.started = false;
1777  
1778    // Set up all inheritable **Backbone.History** properties and methods.
1779    _.extend(History.prototype, Events, {
1780  
1781      // The default interval to poll for hash changes, if necessary, is
1782      // twenty times a second.
1783      interval: 50,
1784  
1785      // Are we at the app root?
1786      atRoot: function() {
1787        var path = this.location.pathname.replace(/[^\/]$/, '$&/');
1788        return path === this.root && !this.getSearch();
1789      },
1790  
1791      // Does the pathname match the root?
1792      matchRoot: function() {
1793        var path = this.decodeFragment(this.location.pathname);
1794        var rootPath = path.slice(0, this.root.length - 1) + '/';
1795        return rootPath === this.root;
1796      },
1797  
1798      // Unicode characters in `location.pathname` are percent encoded so they're
1799      // decoded for comparison. `%25` should not be decoded since it may be part
1800      // of an encoded parameter.
1801      decodeFragment: function(fragment) {
1802        return decodeURI(fragment.replace(/%25/g, '%2525'));
1803      },
1804  
1805      // In IE6, the hash fragment and search params are incorrect if the
1806      // fragment contains `?`.
1807      getSearch: function() {
1808        var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
1809        return match ? match[0] : '';
1810      },
1811  
1812      // Gets the true hash value. Cannot use location.hash directly due to bug
1813      // in Firefox where location.hash will always be decoded.
1814      getHash: function(window) {
1815        var match = (window || this).location.href.match(/#(.*)$/);
1816        return match ? match[1] : '';
1817      },
1818  
1819      // Get the pathname and search params, without the root.
1820      getPath: function() {
1821        var path = this.decodeFragment(
1822          this.location.pathname + this.getSearch()
1823        ).slice(this.root.length - 1);
1824        return path.charAt(0) === '/' ? path.slice(1) : path;
1825      },
1826  
1827      // Get the cross-browser normalized URL fragment from the path or hash.
1828      getFragment: function(fragment) {
1829        if (fragment == null) {
1830          if (this._usePushState || !this._wantsHashChange) {
1831            fragment = this.getPath();
1832          } else {
1833            fragment = this.getHash();
1834          }
1835        }
1836        return fragment.replace(routeStripper, '');
1837      },
1838  
1839      // Start the hash change handling, returning `true` if the current URL matches
1840      // an existing route, and `false` otherwise.
1841      start: function(options) {
1842        if (History.started) throw new Error('Backbone.history has already been started');
1843        History.started = true;
1844  
1845        // Figure out the initial configuration. Do we need an iframe?
1846        // Is pushState desired ... is it available?
1847        this.options          = _.extend({root: '/'}, this.options, options);
1848        this.root             = this.options.root;
1849        this._wantsHashChange = this.options.hashChange !== false;
1850        this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
1851        this._useHashChange   = this._wantsHashChange && this._hasHashChange;
1852        this._wantsPushState  = !!this.options.pushState;
1853        this._hasPushState    = !!(this.history && this.history.pushState);
1854        this._usePushState    = this._wantsPushState && this._hasPushState;
1855        this.fragment         = this.getFragment();
1856  
1857        // Normalize root to always include a leading and trailing slash.
1858        this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1859  
1860        // Transition from hashChange to pushState or vice versa if both are
1861        // requested.
1862        if (this._wantsHashChange && this._wantsPushState) {
1863  
1864          // If we've started off with a route from a `pushState`-enabled
1865          // browser, but we're currently in a browser that doesn't support it...
1866          if (!this._hasPushState && !this.atRoot()) {
1867            var rootPath = this.root.slice(0, -1) || '/';
1868            this.location.replace(rootPath + '#' + this.getPath());
1869            // Return immediately as browser will do redirect to new url
1870            return true;
1871  
1872          // Or if we've started out with a hash-based route, but we're currently
1873          // in a browser where it could be `pushState`-based instead...
1874          } else if (this._hasPushState && this.atRoot()) {
1875            this.navigate(this.getHash(), {replace: true});
1876          }
1877  
1878        }
1879  
1880        // Proxy an iframe to handle location events if the browser doesn't
1881        // support the `hashchange` event, HTML5 history, or the user wants
1882        // `hashChange` but not `pushState`.
1883        if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
1884          this.iframe = document.createElement('iframe');
1885          this.iframe.src = 'javascript:0';
1886          this.iframe.style.display = 'none';
1887          this.iframe.tabIndex = -1;
1888          var body = document.body;
1889          // Using `appendChild` will throw on IE < 9 if the document is not ready.
1890          var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
1891          iWindow.document.open();
1892          iWindow.document.close();
1893          iWindow.location.hash = '#' + this.fragment;
1894        }
1895  
1896        // Add a cross-platform `addEventListener` shim for older browsers.
1897        var addEventListener = window.addEventListener || function(eventName, listener) {
1898          return attachEvent('on' + eventName, listener);
1899        };
1900  
1901        // Depending on whether we're using pushState or hashes, and whether
1902        // 'onhashchange' is supported, determine how we check the URL state.
1903        if (this._usePushState) {
1904          addEventListener('popstate', this.checkUrl, false);
1905        } else if (this._useHashChange && !this.iframe) {
1906          addEventListener('hashchange', this.checkUrl, false);
1907        } else if (this._wantsHashChange) {
1908          this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1909        }
1910  
1911        if (!this.options.silent) return this.loadUrl();
1912      },
1913  
1914      // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1915      // but possibly useful for unit testing Routers.
1916      stop: function() {
1917        // Add a cross-platform `removeEventListener` shim for older browsers.
1918        var removeEventListener = window.removeEventListener || function(eventName, listener) {
1919          return detachEvent('on' + eventName, listener);
1920        };
1921  
1922        // Remove window listeners.
1923        if (this._usePushState) {
1924          removeEventListener('popstate', this.checkUrl, false);
1925        } else if (this._useHashChange && !this.iframe) {
1926          removeEventListener('hashchange', this.checkUrl, false);
1927        }
1928  
1929        // Clean up the iframe if necessary.
1930        if (this.iframe) {
1931          document.body.removeChild(this.iframe);
1932          this.iframe = null;
1933        }
1934  
1935        // Some environments will throw when clearing an undefined interval.
1936        if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
1937        History.started = false;
1938      },
1939  
1940      // Add a route to be tested when the fragment changes. Routes added later
1941      // may override previous routes.
1942      route: function(route, callback) {
1943        this.handlers.unshift({route: route, callback: callback});
1944      },
1945  
1946      // Checks the current URL to see if it has changed, and if it has,
1947      // calls `loadUrl`, normalizing across the hidden iframe.
1948      checkUrl: function(e) {
1949        var current = this.getFragment();
1950  
1951        // If the user pressed the back button, the iframe's hash will have
1952        // changed and we should use that for comparison.
1953        if (current === this.fragment && this.iframe) {
1954          current = this.getHash(this.iframe.contentWindow);
1955        }
1956  
1957        if (current === this.fragment) return false;
1958        if (this.iframe) this.navigate(current);
1959        this.loadUrl();
1960      },
1961  
1962      // Attempt to load the current URL fragment. If a route succeeds with a
1963      // match, returns `true`. If no defined routes matches the fragment,
1964      // returns `false`.
1965      loadUrl: function(fragment) {
1966        // If the root doesn't match, no routes can match either.
1967        if (!this.matchRoot()) return false;
1968        fragment = this.fragment = this.getFragment(fragment);
1969        return _.some(this.handlers, function(handler) {
1970          if (handler.route.test(fragment)) {
1971            handler.callback(fragment);
1972            return true;
1973          }
1974        });
1975      },
1976  
1977      // Save a fragment into the hash history, or replace the URL state if the
1978      // 'replace' option is passed. You are responsible for properly URL-encoding
1979      // the fragment in advance.
1980      //
1981      // The options object can contain `trigger: true` if you wish to have the
1982      // route callback be fired (not usually desirable), or `replace: true`, if
1983      // you wish to modify the current URL without adding an entry to the history.
1984      navigate: function(fragment, options) {
1985        if (!History.started) return false;
1986        if (!options || options === true) options = {trigger: !!options};
1987  
1988        // Normalize the fragment.
1989        fragment = this.getFragment(fragment || '');
1990  
1991        // Don't include a trailing slash on the root.
1992        var rootPath = this.root;
1993        if (fragment === '' || fragment.charAt(0) === '?') {
1994          rootPath = rootPath.slice(0, -1) || '/';
1995        }
1996        var url = rootPath + fragment;
1997  
1998        // Strip the fragment of the query and hash for matching.
1999        fragment = fragment.replace(pathStripper, '');
2000  
2001        // Decode for matching.
2002        var decodedFragment = this.decodeFragment(fragment);
2003  
2004        if (this.fragment === decodedFragment) return;
2005        this.fragment = decodedFragment;
2006  
2007        // If pushState is available, we use it to set the fragment as a real URL.
2008        if (this._usePushState) {
2009          this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
2010  
2011        // If hash changes haven't been explicitly disabled, update the hash
2012        // fragment to store history.
2013        } else if (this._wantsHashChange) {
2014          this._updateHash(this.location, fragment, options.replace);
2015          if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
2016            var iWindow = this.iframe.contentWindow;
2017  
2018            // Opening and closing the iframe tricks IE7 and earlier to push a
2019            // history entry on hash-tag change.  When replace is true, we don't
2020            // want this.
2021            if (!options.replace) {
2022              iWindow.document.open();
2023              iWindow.document.close();
2024            }
2025  
2026            this._updateHash(iWindow.location, fragment, options.replace);
2027          }
2028  
2029        // If you've told us that you explicitly don't want fallback hashchange-
2030        // based history, then `navigate` becomes a page refresh.
2031        } else {
2032          return this.location.assign(url);
2033        }
2034        if (options.trigger) return this.loadUrl(fragment);
2035      },
2036  
2037      // Update the hash location, either replacing the current entry, or adding
2038      // a new one to the browser history.
2039      _updateHash: function(location, fragment, replace) {
2040        if (replace) {
2041          var href = location.href.replace(/(javascript:|#).*$/, '');
2042          location.replace(href + '#' + fragment);
2043        } else {
2044          // Some browsers require that `hash` contains a leading #.
2045          location.hash = '#' + fragment;
2046        }
2047      }
2048  
2049    });
2050  
2051    // Create the default Backbone.history.
2052    Backbone.history = new History;
2053  
2054    // Helpers
2055    // -------
2056  
2057    // Helper function to correctly set up the prototype chain for subclasses.
2058    // Similar to `goog.inherits`, but uses a hash of prototype properties and
2059    // class properties to be extended.
2060    var extend = function(protoProps, staticProps) {
2061      var parent = this;
2062      var child;
2063  
2064      // The constructor function for the new subclass is either defined by you
2065      // (the "constructor" property in your `extend` definition), or defaulted
2066      // by us to simply call the parent constructor.
2067      if (protoProps && _.has(protoProps, 'constructor')) {
2068        child = protoProps.constructor;
2069      } else {
2070        child = function(){ return parent.apply(this, arguments); };
2071      }
2072  
2073      // Add static properties to the constructor function, if supplied.
2074      _.extend(child, parent, staticProps);
2075  
2076      // Set the prototype chain to inherit from `parent`, without calling
2077      // `parent`'s constructor function and add the prototype properties.
2078      child.prototype = _.create(parent.prototype, protoProps);
2079      child.prototype.constructor = child;
2080  
2081      // Set a convenience property in case the parent's prototype is needed
2082      // later.
2083      child.__super__ = parent.prototype;
2084  
2085      return child;
2086    };
2087  
2088    // Set up inheritance for the model, collection, router, view and history.
2089    Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
2090  
2091    // Throw an error when a URL is needed, and none is supplied.
2092    var urlError = function() {
2093      throw new Error('A "url" property or function must be specified');
2094    };
2095  
2096    // Wrap an optional error callback with a fallback error event.
2097    var wrapError = function(model, options) {
2098      var error = options.error;
2099      options.error = function(resp) {
2100        if (error) error.call(options.context, model, resp, options);
2101        model.trigger('error', model, resp, options);
2102      };
2103    };
2104  
2105    return Backbone;
2106  });


Generated: Sun Dec 22 01:00:02 2024 Cross-referenced by PHPXref 0.7.1