PageRenderTime 71ms CodeModel.GetById 2ms app.highlight 58ms RepoModel.GetById 1ms app.codeStats 1ms

/www/protected/extensions/admin/assets/js/libs/backbone/0.5.3-optamd3/backbone.js

https://bitbucket.org/badenkov/demo
JavaScript | 1139 lines | 688 code | 147 blank | 304 comment | 256 complexity | 363aa9c0a6c9028f80516921820dee5d MD5 | raw file
   1//     Backbone.js 0.5.3
   2//     (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
   3//     Backbone may be freely distributed under the MIT license.
   4//     For all details and documentation:
   5//     http://documentcloud.github.com/backbone
   6
   7
   8(function(root, factory) {
   9  // Set up Backbone appropriately for the environment.
  10  if (typeof exports !== 'undefined') {
  11    // Node/CommonJS, no need for jQuery in that case.
  12    factory(root, exports, require('underscore'));
  13  } else if (typeof define === 'function' && define.amd) {
  14    // AMD
  15    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
  16      factory(root, exports, _, $);
  17    });
  18  } else {
  19    // Browser globals
  20    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender));
  21  }
  22}(this, function(root, Backbone, _, $) {
  23
  24  // Initial Setup
  25  // -------------
  26
  27  // Save the previous value of the `Backbone` variable.
  28  var previousBackbone = root.Backbone;
  29
  30  // Create a local reference to slice.
  31  var slice = Array.prototype.slice;
  32
  33  // Current version of the library. Keep in sync with `package.json`.
  34  Backbone.VERSION = '0.5.3';
  35
  36  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  37  // to its previous owner. Returns a reference to this Backbone object.
  38  Backbone.noConflict = function() {
  39    root.Backbone = previousBackbone;
  40    return Backbone;
  41  };
  42
  43  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option will
  44  // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a
  45  // `X-Http-Method-Override` header.
  46  Backbone.emulateHTTP = false;
  47
  48  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  49  // `application/json` requests ... will encode the body as
  50  // `application/x-www-form-urlencoded` instead and will send the model in a
  51  // form param named `model`.
  52  Backbone.emulateJSON = false;
  53
  54  // Backbone.Events
  55  // -----------------
  56
  57  // A module that can be mixed in to *any object* in order to provide it with
  58  // custom events. You may `bind` or `unbind` a callback function to an event;
  59  // `trigger`-ing an event fires all callbacks in succession.
  60  //
  61  //     var object = {};
  62  //     _.extend(object, Backbone.Events);
  63  //     object.bind('expand', function(){ alert('expanded'); });
  64  //     object.trigger('expand');
  65  //
  66  Backbone.Events = {
  67
  68    // Bind an event, specified by a string name, `ev`, to a `callback` function.
  69    // Passing `"all"` will bind the callback to all events fired.
  70    bind : function(ev, callback, context) {
  71      var calls = this._callbacks || (this._callbacks = {});
  72      var list  = calls[ev] || (calls[ev] = {});
  73      var tail = list.tail || (list.tail = list.next = {});
  74      tail.callback = callback;
  75      tail.context = context;
  76      list.tail = tail.next = {};
  77      return this;
  78    },
  79
  80    // Remove one or many callbacks. If `callback` is null, removes all
  81    // callbacks for the event. If `ev` is null, removes all bound callbacks
  82    // for all events.
  83    unbind : function(ev, callback) {
  84      var calls, node, prev;
  85      if (!ev) {
  86        this._callbacks = null;
  87      } else if (calls = this._callbacks) {
  88        if (!callback) {
  89          calls[ev] = {};
  90        } else if (node = calls[ev]) {
  91          while ((prev = node) && (node = node.next)) {
  92            if (node.callback !== callback) continue;
  93            prev.next = node.next;
  94            node.context = node.callback = null;
  95            break;
  96          }
  97        }
  98      }
  99      return this;
 100    },
 101
 102    // Trigger an event, firing all bound callbacks. Callbacks are passed the
 103    // same arguments as `trigger` is, apart from the event name.
 104    // Listening for `"all"` passes the true event name as the first argument.
 105    trigger : function(eventName) {
 106      var node, calls, callback, args, ev, events = ['all', eventName];
 107      if (!(calls = this._callbacks)) return this;
 108      while (ev = events.pop()) {
 109        if (!(node = calls[ev])) continue;
 110        args = ev == 'all' ? arguments : slice.call(arguments, 1);
 111        while (node = node.next) if (callback = node.callback) callback.apply(node.context || this, args);
 112      }
 113      return this;
 114    }
 115
 116  };
 117
 118  // Backbone.Model
 119  // --------------
 120
 121  // Create a new model, with defined attributes. A client id (`cid`)
 122  // is automatically generated and assigned for you.
 123  Backbone.Model = function(attributes, options) {
 124    var defaults;
 125    attributes || (attributes = {});
 126    if (options && options.parse) attributes = this.parse(attributes);
 127    if (defaults = getValue(this, 'defaults')) {
 128      attributes = _.extend({}, defaults, attributes);
 129    }
 130    this.attributes = {};
 131    this._escapedAttributes = {};
 132    this.cid = _.uniqueId('c');
 133    this.set(attributes, {silent : true});
 134    this._changed = false;
 135    this._previousAttributes = _.clone(this.attributes);
 136    if (options && options.collection) this.collection = options.collection;
 137    this.initialize(attributes, options);
 138  };
 139
 140  // Attach all inheritable methods to the Model prototype.
 141  _.extend(Backbone.Model.prototype, Backbone.Events, {
 142
 143    // Has the item been changed since the last `"change"` event?
 144    _changed : false,
 145
 146    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
 147    // CouchDB users may want to set this to `"_id"`.
 148    idAttribute : 'id',
 149
 150    // Initialize is an empty function by default. Override it with your own
 151    // initialization logic.
 152    initialize : function(){},
 153
 154    // Return a copy of the model's `attributes` object.
 155    toJSON : function() {
 156      return _.clone(this.attributes);
 157    },
 158
 159    // Get the value of an attribute.
 160    get : function(attr) {
 161      return this.attributes[attr];
 162    },
 163
 164    // Get the HTML-escaped value of an attribute.
 165    escape : function(attr) {
 166      var html;
 167      if (html = this._escapedAttributes[attr]) return html;
 168      var val = this.attributes[attr];
 169      return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
 170    },
 171
 172    // Returns `true` if the attribute contains a value that is not null
 173    // or undefined.
 174    has : function(attr) {
 175      return this.attributes[attr] != null;
 176    },
 177
 178    // Set a hash of model attributes on the object, firing `"change"` unless you
 179    // choose to silence it.
 180    set : function(key, value, options) {
 181      var attrs;
 182      if (_.isObject(key) || key == null) {
 183        attrs = key;
 184        options = value;
 185      } else {
 186        attrs = {};
 187        attrs[key] = value;
 188      }
 189
 190      // Extract attributes and options.
 191      options || (options = {});
 192      if (!attrs) return this;
 193      if (attrs.attributes) attrs = attrs.attributes;
 194      if (options.unset) for (var attr in attrs) attrs[attr] = void 0;
 195      var now = this.attributes, escaped = this._escapedAttributes;
 196
 197      // Run validation.
 198      if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
 199
 200      // Check for changes of `id`.
 201      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
 202
 203      // We're about to start triggering change events.
 204      var alreadyChanging = this._changing;
 205      this._changing = true;
 206
 207      // Update attributes.
 208      for (var attr in attrs) {
 209        var val = attrs[attr];
 210        if (!_.isEqual(now[attr], val) || (options.unset && (attr in now))) {
 211          options.unset ? delete now[attr] : now[attr] = val;
 212          delete escaped[attr];
 213          this._changed = true;
 214          if (!options.silent) this.trigger('change:' + attr, this, val, options);
 215        }
 216      }
 217
 218      // Fire the `"change"` event, if the model has been changed.
 219      if (!alreadyChanging) {
 220        if (!options.silent && this._changed) this.change(options);
 221        this._changing = false;
 222      }
 223      return this;
 224    },
 225
 226    // Remove an attribute from the model, firing `"change"` unless you choose
 227    // to silence it. `unset` is a noop if the attribute doesn't exist.
 228    unset : function(attr, options) {
 229      (options || (options = {})).unset = true;
 230      return this.set(attr, null, options);
 231    },
 232
 233    // Clear all attributes on the model, firing `"change"` unless you choose
 234    // to silence it.
 235    clear : function(options) {
 236      (options || (options = {})).unset = true;
 237      return this.set(_.clone(this.attributes), options);
 238    },
 239
 240    // Fetch the model from the server. If the server's representation of the
 241    // model differs from its current attributes, they will be overriden,
 242    // triggering a `"change"` event.
 243    fetch : function(options) {
 244      options || (options = {});
 245      var model = this;
 246      var success = options.success;
 247      options.success = function(resp, status, xhr) {
 248        if (!model.set(model.parse(resp, xhr), options)) return false;
 249        if (success) success(model, resp);
 250      };
 251      options.error = wrapError(options.error, model, options);
 252      return (this.sync || Backbone.sync).call(this, 'read', this, options);
 253    },
 254
 255    // Set a hash of model attributes, and sync the model to the server.
 256    // If the server returns an attributes hash that differs, the model's
 257    // state will be `set` again.
 258    save : function(attrs, options) {
 259      options || (options = {});
 260      if (attrs && !this.set(attrs, options)) return false;
 261      var model = this;
 262      var success = options.success;
 263      options.success = function(resp, status, xhr) {
 264        if (!model.set(model.parse(resp, xhr), options)) return false;
 265        if (success) success(model, resp, xhr);
 266      };
 267      options.error = wrapError(options.error, model, options);
 268      var method = this.isNew() ? 'create' : 'update';
 269      return (this.sync || Backbone.sync).call(this, method, this, options);
 270    },
 271
 272    // Destroy this model on the server if it was already persisted. Upon success, the model is removed
 273    // from its collection, if it has one.
 274    destroy : function(options) {
 275      options || (options = {});
 276      if (this.isNew()) return this.trigger('destroy', this, this.collection, options);
 277      var model = this;
 278      var success = options.success;
 279      options.success = function(resp) {
 280        model.trigger('destroy', model, model.collection, options);
 281        if (success) success(model, resp);
 282      };
 283      options.error = wrapError(options.error, model, options);
 284      return (this.sync || Backbone.sync).call(this, 'delete', this, options);
 285    },
 286
 287    // Default URL for the model's representation on the server -- if you're
 288    // using Backbone's restful methods, override this to change the endpoint
 289    // that will be called.
 290    url : function() {
 291      var base = getValue(this.collection, 'url') || this.urlRoot || urlError();
 292      if (this.isNew()) return base;
 293      return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
 294    },
 295
 296    // **parse** converts a response into the hash of attributes to be `set` on
 297    // the model. The default implementation is just to pass the response along.
 298    parse : function(resp, xhr) {
 299      return resp;
 300    },
 301
 302    // Create a new model with identical attributes to this one.
 303    clone : function() {
 304      return new this.constructor(this);
 305    },
 306
 307    // A model is new if it has never been saved to the server, and lacks an id.
 308    isNew : function() {
 309      return this.id == null;
 310    },
 311
 312    // Call this method to manually fire a `change` event for this model.
 313    // Calling this will cause all objects observing the model to update.
 314    change : function(options) {
 315      this.trigger('change', this, options);
 316      this._previousAttributes = _.clone(this.attributes);
 317      this._changed = false;
 318    },
 319
 320    // Determine if the model has changed since the last `"change"` event.
 321    // If you specify an attribute name, determine if that attribute has changed.
 322    hasChanged : function(attr) {
 323      if (attr) return this._previousAttributes[attr] != this.attributes[attr];
 324      return this._changed;
 325    },
 326
 327    // Return an object containing all the attributes that have changed, or false
 328    // if there are no changed attributes. Useful for determining what parts of a
 329    // view need to be updated and/or what attributes need to be persisted to
 330    // the server. Unset attributes will be set to undefined.
 331    changedAttributes : function(now) {
 332      if (!this._changed) return false;
 333      now || (now = this.attributes);
 334      var changed = false, old = this._previousAttributes;
 335      for (var attr in now) {
 336        if (_.isEqual(old[attr], now[attr])) continue;
 337        (changed || (changed = {}))[attr] = now[attr];
 338      }
 339      for (var attr in old) {
 340        if (!(attr in now)) (changed || (changed = {}))[attr] = void 0;
 341      }
 342      return changed;
 343    },
 344
 345    // Get the previous value of an attribute, recorded at the time the last
 346    // `"change"` event was fired.
 347    previous : function(attr) {
 348      if (!attr || !this._previousAttributes) return null;
 349      return this._previousAttributes[attr];
 350    },
 351
 352    // Get all of the attributes of the model at the time of the previous
 353    // `"change"` event.
 354    previousAttributes : function() {
 355      return _.clone(this._previousAttributes);
 356    },
 357
 358    // Run validation against a set of incoming attributes, returning `true`
 359    // if all is well. If a specific `error` callback has been passed,
 360    // call that instead of firing the general `"error"` event.
 361    _performValidation : function(attrs, options) {
 362      var error = this.validate(attrs, options);
 363      if (error) {
 364        if (options.error) {
 365          options.error(this, error, options);
 366        } else {
 367          this.trigger('error', this, error, options);
 368        }
 369        return false;
 370      }
 371      return true;
 372    }
 373
 374  });
 375
 376  // Backbone.Collection
 377  // -------------------
 378
 379  // Provides a standard collection class for our sets of models, ordered
 380  // or unordered. If a `comparator` is specified, the Collection will maintain
 381  // its models in sort order, as they're added and removed.
 382  Backbone.Collection = function(models, options) {
 383    options || (options = {});
 384    if (options.comparator) this.comparator = options.comparator;
 385    _.bindAll(this, '_onModelEvent', '_removeReference');
 386    this._reset();
 387    if (models) this.reset(models, {silent: true});
 388    this.initialize.apply(this, arguments);
 389  };
 390
 391  // Define the Collection's inheritable methods.
 392  _.extend(Backbone.Collection.prototype, Backbone.Events, {
 393
 394    // The default model for a collection is just a **Backbone.Model**.
 395    // This should be overridden in most cases.
 396    model : Backbone.Model,
 397
 398    // Initialize is an empty function by default. Override it with your own
 399    // initialization logic.
 400    initialize : function(){},
 401
 402    // The JSON representation of a Collection is an array of the
 403    // models' attributes.
 404    toJSON : function() {
 405      return this.map(function(model){ return model.toJSON(); });
 406    },
 407
 408    // Add a model, or list of models to the set. Pass **silent** to avoid
 409    // firing the `added` event for every new model.
 410    add : function(models, options) {
 411      if (_.isArray(models)) {
 412        for (var i = 0, l = models.length; i < l; i++) {
 413          if (options && (options.at == +options.at) && i) options.at += 1;
 414          this._add(models[i], options);
 415        }
 416      } else {
 417        this._add(models, options);
 418      }
 419      return this;
 420    },
 421
 422    // Remove a model, or a list of models from the set. Pass silent to avoid
 423    // firing the `removed` event for every model removed.
 424    remove : function(models, options) {
 425      if (_.isArray(models)) {
 426        for (var i = 0, l = models.length; i < l; i++) {
 427          this._remove(models[i], options);
 428        }
 429      } else {
 430        this._remove(models, options);
 431      }
 432      return this;
 433    },
 434
 435    // Get a model from the set by id.
 436    get : function(id) {
 437      if (id == null) return null;
 438      return this._byId[id.id != null ? id.id : id];
 439    },
 440
 441    // Get a model from the set by client id.
 442    getByCid : function(cid) {
 443      return cid && this._byCid[cid.cid || cid];
 444    },
 445
 446    // Get the model at the given index.
 447    at : function(index) {
 448      return this.models[index];
 449    },
 450
 451    // Force the collection to re-sort itself. You don't need to call this under normal
 452    // circumstances, as the set will maintain sort order as each item is added.
 453    sort : function(options) {
 454      options || (options = {});
 455      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
 456      this.models = this.sortBy(this.comparator);
 457      if (!options.silent) this.trigger('reset', this, options);
 458      return this;
 459    },
 460
 461    // Pluck an attribute from each model in the collection.
 462    pluck : function(attr) {
 463      return _.map(this.models, function(model){ return model.get(attr); });
 464    },
 465
 466    // When you have more items than you want to add or remove individually,
 467    // you can reset the entire set with a new list of models, without firing
 468    // any `added` or `removed` events. Fires `reset` when finished.
 469    reset : function(models, options) {
 470      models  || (models = []);
 471      options || (options = {});
 472      this.each(this._removeReference);
 473      this._reset();
 474      this.add(models, {silent: true, parse: options.parse});
 475      if (!options.silent) this.trigger('reset', this, options);
 476      return this;
 477    },
 478
 479    // Fetch the default set of models for this collection, resetting the
 480    // collection when they arrive. If `add: true` is passed, appends the
 481    // models to the collection instead of resetting.
 482    fetch : function(options) {
 483      options || (options = {});
 484      if (options.parse === undefined) options.parse = true;
 485      var collection = this;
 486      var success = options.success;
 487      options.success = function(resp, status, xhr) {
 488        collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
 489        if (success) success(collection, resp);
 490      };
 491      options.error = wrapError(options.error, collection, options);
 492      return (this.sync || Backbone.sync).call(this, 'read', this, options);
 493    },
 494
 495    // Create a new instance of a model in this collection. After the model
 496    // has been created on the server, it will be added to the collection.
 497    // Returns the model, or 'false' if validation on a new model fails.
 498    create : function(model, options) {
 499      var coll = this;
 500      options || (options = {});
 501      model = this._prepareModel(model, options);
 502      if (!model) return false;
 503      var success = options.success;
 504      options.success = function(nextModel, resp, xhr) {
 505        coll.add(nextModel, options);
 506        if (success) success(nextModel, resp, xhr);
 507      };
 508      model.save(null, options);
 509      return model;
 510    },
 511
 512    // **parse** converts a response into a list of models to be added to the
 513    // collection. The default implementation is just to pass it through.
 514    parse : function(resp, xhr) {
 515      return resp;
 516    },
 517
 518    // Proxy to _'s chain. Can't be proxied the same way the rest of the
 519    // underscore methods are proxied because it relies on the underscore
 520    // constructor.
 521    chain : function () {
 522      return _(this.models).chain();
 523    },
 524
 525    // Reset all internal state. Called when the collection is reset.
 526    _reset : function(options) {
 527      this.length = 0;
 528      this.models = [];
 529      this._byId  = {};
 530      this._byCid = {};
 531    },
 532
 533    // Prepare a model to be added to this collection
 534    _prepareModel : function(model, options) {
 535      if (!(model instanceof Backbone.Model)) {
 536        var attrs = model;
 537        model = new this.model(attrs, {collection: this, parse: options.parse});
 538        if (model.validate && !model._performValidation(model.attributes, options)) model = false;
 539      } else if (!model.collection) {
 540        model.collection = this;
 541      }
 542      return model;
 543    },
 544
 545    // Internal implementation of adding a single model to the set, updating
 546    // hash indexes for `id` and `cid` lookups.
 547    // Returns the model, or 'false' if validation on a new model fails.
 548    _add : function(model, options) {
 549      options || (options = {});
 550      model = this._prepareModel(model, options);
 551      if (!model) return false;
 552      var already = this.getByCid(model);
 553      if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
 554      this._byId[model.id] = model;
 555      this._byCid[model.cid] = model;
 556      var index = options.at != null ? options.at :
 557                  this.comparator ? this.sortedIndex(model, this.comparator) :
 558                  this.length;
 559      this.models.splice(index, 0, model);
 560      model.bind('all', this._onModelEvent);
 561      this.length++;
 562      options.index = index;
 563      if (!options.silent) model.trigger('add', model, this, options);
 564      return model;
 565    },
 566
 567    // Internal implementation of removing a single model from the set, updating
 568    // hash indexes for `id` and `cid` lookups.
 569    _remove : function(model, options) {
 570      options || (options = {});
 571      model = this.getByCid(model) || this.get(model);
 572      if (!model) return null;
 573      delete this._byId[model.id];
 574      delete this._byCid[model.cid];
 575      var index = this.indexOf(model);
 576      this.models.splice(index, 1);
 577      this.length--;
 578      options.index = index;
 579      if (!options.silent) model.trigger('remove', model, this, options);
 580      this._removeReference(model);
 581      return model;
 582    },
 583
 584    // Internal method to remove a model's ties to a collection.
 585    _removeReference : function(model) {
 586      if (this == model.collection) {
 587        delete model.collection;
 588      }
 589      model.unbind('all', this._onModelEvent);
 590    },
 591
 592    // Internal method called every time a model in the set fires an event.
 593    // Sets need to update their indexes when models change ids. All other
 594    // events simply proxy through. "add" and "remove" events that originate
 595    // in other collections are ignored.
 596    _onModelEvent : function(ev, model, collection, options) {
 597      if ((ev == 'add' || ev == 'remove') && collection != this) return;
 598      if (ev == 'destroy') {
 599        this._remove(model, options);
 600      }
 601      if (model && ev === 'change:' + model.idAttribute) {
 602        delete this._byId[model.previous(model.idAttribute)];
 603        this._byId[model.id] = model;
 604      }
 605      this.trigger.apply(this, arguments);
 606    }
 607
 608  });
 609
 610  // Underscore methods that we want to implement on the Collection.
 611  var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
 612    'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
 613    'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
 614    'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty', 'groupBy'];
 615
 616  // Mix in each Underscore method as a proxy to `Collection#models`.
 617  _.each(methods, function(method) {
 618    Backbone.Collection.prototype[method] = function() {
 619      return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
 620    };
 621  });
 622
 623  // Backbone.Router
 624  // -------------------
 625
 626  // Routers map faux-URLs to actions, and fire events when routes are
 627  // matched. Creating a new one sets its `routes` hash, if not set statically.
 628  Backbone.Router = function(options) {
 629    options || (options = {});
 630    if (options.routes) this.routes = options.routes;
 631    this._bindRoutes();
 632    this.initialize.apply(this, arguments);
 633  };
 634
 635  // Cached regular expressions for matching named param parts and splatted
 636  // parts of route strings.
 637  var namedParam    = /:\w+/g;
 638  var splatParam    = /\*\w+/g;
 639  var escapeRegExp  = /[-[\]{}()+?.,\\^$|#\s]/g;
 640
 641  // Set up all inheritable **Backbone.Router** properties and methods.
 642  _.extend(Backbone.Router.prototype, Backbone.Events, {
 643
 644    // Initialize is an empty function by default. Override it with your own
 645    // initialization logic.
 646    initialize : function(){},
 647
 648    // Manually bind a single named route to a callback. For example:
 649    //
 650    //     this.route('search/:query/p:num', 'search', function(query, num) {
 651    //       ...
 652    //     });
 653    //
 654    route : function(route, name, callback) {
 655      Backbone.history || (Backbone.history = new Backbone.History);
 656      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
 657      Backbone.history.route(route, _.bind(function(fragment) {
 658        var args = this._extractParameters(route, fragment);
 659        callback && callback.apply(this, args);
 660        this.trigger.apply(this, ['route:' + name].concat(args));
 661      }, this));
 662    },
 663
 664    // Simple proxy to `Backbone.history` to save a fragment into the history.
 665    navigate : function(fragment, options) {
 666      Backbone.history.navigate(fragment, options);
 667    },
 668
 669    // Bind all defined routes to `Backbone.history`. We have to reverse the
 670    // order of the routes here to support behavior where the most general
 671    // routes can be defined at the bottom of the route map.
 672    _bindRoutes : function() {
 673      if (!this.routes) return;
 674      var routes = [];
 675      for (var route in this.routes) {
 676        routes.unshift([route, this.routes[route]]);
 677      }
 678      for (var i = 0, l = routes.length; i < l; i++) {
 679        this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
 680      }
 681    },
 682
 683    // Convert a route string into a regular expression, suitable for matching
 684    // against the current location hash.
 685    _routeToRegExp : function(route) {
 686      route = route.replace(escapeRegExp, '\\$&')
 687                   .replace(namedParam, '([^\/]*)')
 688                   .replace(splatParam, '(.*?)');
 689      return new RegExp('^' + route + '$');
 690    },
 691
 692    // Given a route, and a URL fragment that it matches, return the array of
 693    // extracted parameters.
 694    _extractParameters : function(route, fragment) {
 695      return route.exec(fragment).slice(1);
 696    }
 697
 698  });
 699
 700  // Backbone.History
 701  // ----------------
 702
 703  // Handles cross-browser history management, based on URL fragments. If the
 704  // browser does not support `onhashchange`, falls back to polling.
 705  Backbone.History = function() {
 706    this.handlers = [];
 707    _.bindAll(this, 'checkUrl');
 708  };
 709
 710  // Cached regex for cleaning hashes.
 711  var hashStrip = /^#/;
 712
 713  // Cached regex for detecting MSIE.
 714  var isExplorer = /msie [\w.]+/;
 715
 716  // Has the history handling already been started?
 717  var historyStarted = false;
 718
 719  // Set up all inheritable **Backbone.History** properties and methods.
 720  _.extend(Backbone.History.prototype, {
 721
 722    // The default interval to poll for hash changes, if necessary, is
 723    // twenty times a second.
 724    interval: 50,
 725
 726    // Get the cross-browser normalized URL fragment, either from the URL,
 727    // the hash, or the override.
 728    getFragment : function(fragment, forcePushState) {
 729      if (fragment == null) {
 730        if (this._hasPushState || forcePushState) {
 731          fragment = window.location.pathname;
 732          var search = window.location.search;
 733          if (search) fragment += search;
 734        } else {
 735          fragment = window.location.hash;
 736        }
 737      }
 738      fragment = decodeURIComponent(fragment.replace(hashStrip, ''));
 739      if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
 740      return fragment;
 741    },
 742
 743    // Start the hash change handling, returning `true` if the current URL matches
 744    // an existing route, and `false` otherwise.
 745    start : function(options) {
 746
 747      // Figure out the initial configuration. Do we need an iframe?
 748      // Is pushState desired ... is it available?
 749      if (historyStarted) throw new Error("Backbone.history has already been started");
 750      this.options          = _.extend({}, {root: '/'}, this.options, options);
 751      this._wantsPushState  = !!this.options.pushState;
 752      this._hasPushState    = !!(this.options.pushState && window.history && window.history.pushState);
 753      var fragment          = this.getFragment();
 754      var docMode           = document.documentMode;
 755      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
 756      if (oldIE) {
 757        this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
 758        this.navigate(fragment);
 759      }
 760
 761      // Depending on whether we're using pushState or hashes, and whether
 762      // 'onhashchange' is supported, determine how we check the URL state.
 763      if (this._hasPushState) {
 764        $(window).bind('popstate', this.checkUrl);
 765      } else if ('onhashchange' in window && !oldIE) {
 766        $(window).bind('hashchange', this.checkUrl);
 767      } else {
 768        setInterval(this.checkUrl, this.interval);
 769      }
 770
 771      // Determine if we need to change the base url, for a pushState link
 772      // opened by a non-pushState browser.
 773      this.fragment = fragment;
 774      historyStarted = true;
 775      var loc = window.location;
 776      var atRoot  = loc.pathname == this.options.root;
 777      if (this._wantsPushState && !this._hasPushState && !atRoot) {
 778        this.fragment = this.getFragment(null, true);
 779        window.location.replace(this.options.root + '#' + this.fragment);
 780        // Return immediately as browser will do redirect to new url
 781        return true;
 782      } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
 783        this.fragment = loc.hash.replace(hashStrip, '');
 784        window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
 785      }
 786
 787      if (!this.options.silent) {
 788        return this.loadUrl();
 789      }
 790    },
 791
 792    // Add a route to be tested when the fragment changes. Routes added later may
 793    // override previous routes.
 794    route : function(route, callback) {
 795      this.handlers.unshift({route : route, callback : callback});
 796    },
 797
 798    // Checks the current URL to see if it has changed, and if it has,
 799    // calls `loadUrl`, normalizing across the hidden iframe.
 800    checkUrl : function(e) {
 801      var current = this.getFragment();
 802      if (current == this.fragment && this.iframe) current = this.getFragment(this.iframe.location.hash);
 803      if (current == this.fragment || current == decodeURIComponent(this.fragment)) return false;
 804      if (this.iframe) this.navigate(current);
 805      this.loadUrl() || this.loadUrl(window.location.hash);
 806    },
 807
 808    // Attempt to load the current URL fragment. If a route succeeds with a
 809    // match, returns `true`. If no defined routes matches the fragment,
 810    // returns `false`.
 811    loadUrl : function(fragmentOverride) {
 812      var fragment = this.fragment = this.getFragment(fragmentOverride);
 813      var matched = _.any(this.handlers, function(handler) {
 814        if (handler.route.test(fragment)) {
 815          handler.callback(fragment);
 816          return true;
 817        }
 818      });
 819      return matched;
 820    },
 821
 822    // Save a fragment into the hash history, or replace the URL state if the
 823    // 'replace' option is passed. You are responsible for properly URL-encoding
 824    // the fragment in advance.
 825    //
 826    // The options object can contain `trigger: true` if you wish to have the
 827    // route callback be fired (not usually desirable), or `replace: true`, if
 828    // you which to modify the current URL without adding an entry to the history.
 829    navigate : function(fragment, options) {
 830      if (!options || options === true) options = {trigger: options};
 831      var frag = (fragment || '').replace(hashStrip, '');
 832      if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return;
 833      if (this._hasPushState) {
 834        if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
 835        this.fragment = frag;
 836        window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);
 837      } else {
 838        this.fragment = frag;
 839        this._updateHash(window.location, frag, options.replace);
 840        if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) {
 841          // Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
 842          // When replace is true, we don't want this.
 843          if(!options.replace) this.iframe.document.open().close();
 844          this._updateHash(this.iframe.location, frag, options.replace);
 845        }
 846      }
 847      if (options.trigger) this.loadUrl(fragment);
 848    },
 849
 850    // Update the hash location, either replacing the current entry, or adding
 851    // a new one to the browser history.
 852    _updateHash: function(location, fragment, replace) {
 853      if (replace) {
 854        location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
 855      } else {
 856        location.hash = fragment;
 857      }
 858    }
 859  });
 860
 861  // Backbone.View
 862  // -------------
 863
 864  // Creating a Backbone.View creates its initial element outside of the DOM,
 865  // if an existing element is not provided...
 866  Backbone.View = function(options) {
 867    this.cid = _.uniqueId('view');
 868    this._configure(options || {});
 869    this._ensureElement();
 870    this.delegateEvents();
 871    this.initialize.apply(this, arguments);
 872  };
 873
 874  // Cached regex to split keys for `delegate`.
 875  var eventSplitter = /^(\S+)\s*(.*)$/;
 876
 877  // List of view options to be merged as properties.
 878  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
 879
 880  // Set up all inheritable **Backbone.View** properties and methods.
 881  _.extend(Backbone.View.prototype, Backbone.Events, {
 882
 883    // The default `tagName` of a View's element is `"div"`.
 884    tagName : 'div',
 885
 886    // jQuery delegate for element lookup, scoped to DOM elements within the
 887    // current view. This should be prefered to global lookups where possible.
 888    $ : function(selector) {
 889      return (selector == null) ? $(this.el) : $(selector, this.el);
 890    },
 891
 892    // Initialize is an empty function by default. Override it with your own
 893    // initialization logic.
 894    initialize : function(){},
 895
 896    // **render** is the core function that your view should override, in order
 897    // to populate its element (`this.el`), with the appropriate HTML. The
 898    // convention is for **render** to always return `this`.
 899    render : function() {
 900      return this;
 901    },
 902
 903    // Remove this view from the DOM. Note that the view isn't present in the
 904    // DOM by default, so calling this method may be a no-op.
 905    remove : function() {
 906      $(this.el).remove();
 907      return this;
 908    },
 909
 910    // For small amounts of DOM Elements, where a full-blown template isn't
 911    // needed, use **make** to manufacture elements, one at a time.
 912    //
 913    //     var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
 914    //
 915    make : function(tagName, attributes, content) {
 916      var el = document.createElement(tagName);
 917      if (attributes) $(el).attr(attributes);
 918      if (content) $(el).html(content);
 919      return el;
 920    },
 921
 922    // Set callbacks, where `this.events` is a hash of
 923    //
 924    // *{"event selector": "callback"}*
 925    //
 926    //     {
 927    //       'mousedown .title':  'edit',
 928    //       'click .button':     'save'
 929    //     }
 930    //
 931    // pairs. Callbacks will be bound to the view, with `this` set properly.
 932    // Uses event delegation for efficiency.
 933    // Omitting the selector binds the event to `this.el`.
 934    // This only works for delegate-able events: not `focus`, `blur`, and
 935    // not `change`, `submit`, and `reset` in Internet Explorer.
 936    delegateEvents : function(events) {
 937      if (!(events || (events = getValue(this, 'events')))) return;
 938      this.undelegateEvents();
 939      for (var key in events) {
 940        var method = this[events[key]];
 941        if (!method) throw new Error('Event "' + events[key] + '" does not exist');
 942        var match = key.match(eventSplitter);
 943        var eventName = match[1], selector = match[2];
 944        method = _.bind(method, this);
 945        eventName += '.delegateEvents' + this.cid;
 946        if (selector === '') {
 947          $(this.el).bind(eventName, method);
 948        } else {
 949          $(this.el).delegate(selector, eventName, method);
 950        }
 951      }
 952    },
 953
 954    // Clears all callbacks previously bound to the view with `delegateEvents`.
 955    undelegateEvents : function() {
 956      $(this.el).unbind('.delegateEvents' + this.cid);
 957    },
 958
 959    // Performs the initial configuration of a View with a set of options.
 960    // Keys with special meaning *(model, collection, id, className)*, are
 961    // attached directly to the view.
 962    _configure : function(options) {
 963      if (this.options) options = _.extend({}, this.options, options);
 964      for (var i = 0, l = viewOptions.length; i < l; i++) {
 965        var attr = viewOptions[i];
 966        if (options[attr]) this[attr] = options[attr];
 967      }
 968      this.options = options;
 969    },
 970
 971    // Ensure that the View has a DOM element to render into.
 972    // If `this.el` is a string, pass it through `$()`, take the first
 973    // matching element, and re-assign it to `el`. Otherwise, create
 974    // an element from the `id`, `className` and `tagName` properties.
 975    _ensureElement : function() {
 976      if (!this.el) {
 977        var attrs = this.attributes || {};
 978        if (this.id) attrs.id = this.id;
 979        if (this.className) attrs['class'] = this.className;
 980        this.el = this.make(this.tagName, attrs);
 981      } else if (_.isString(this.el)) {
 982        this.el = $(this.el).get(0);
 983      }
 984    }
 985
 986  });
 987
 988  // The self-propagating extend function that Backbone classes use.
 989  var extend = function (protoProps, classProps) {
 990    var child = inherits(this, protoProps, classProps);
 991    child.extend = this.extend;
 992    return child;
 993  };
 994
 995  // Set up inheritance for the model, collection, and view.
 996  Backbone.Model.extend = Backbone.Collection.extend =
 997    Backbone.Router.extend = Backbone.View.extend = extend;
 998
 999  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1000  var methodMap = {
1001    'create': 'POST',
1002    'update': 'PUT',
1003    'delete': 'DELETE',
1004    'read'  : 'GET'
1005  };
1006
1007  // Backbone.sync
1008  // -------------
1009
1010  // Override this function to change the manner in which Backbone persists
1011  // models to the server. You will be passed the type of request, and the
1012  // model in question. By default, makes a RESTful Ajax request
1013  // to the model's `url()`. Some possible customizations could be:
1014  //
1015  // * Use `setTimeout` to batch rapid-fire updates into a single request.
1016  // * Send up the models as XML instead of JSON.
1017  // * Persist models via WebSockets instead of Ajax.
1018  //
1019  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1020  // as `POST`, with a `_method` parameter containing the true HTTP method,
1021  // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
1022  // `application/json` with the model in a param named `model`.
1023  // Useful when interfacing with server-side languages like **PHP** that make
1024  // it difficult to read the body of `PUT` requests.
1025  Backbone.sync = function(method, model, options) {
1026    var type = methodMap[method];
1027
1028    // Default JSON-request options.
1029    var params = {type : type, dataType : 'json'};
1030
1031    // Ensure that we have a URL.
1032    if (!options.url) {
1033      params.url = getValue(model, 'url') || urlError();
1034    }
1035
1036    // Ensure that we have the appropriate request data.
1037    if (!options.data && model && (method == 'create' || method == 'update')) {
1038      params.contentType = 'application/json';
1039      params.data = JSON.stringify(model.toJSON());
1040    }
1041
1042    // For older servers, emulate JSON by encoding the request into an HTML-form.
1043    if (Backbone.emulateJSON) {
1044      params.contentType = 'application/x-www-form-urlencoded';
1045      params.data = params.data ? {model : params.data} : {};
1046    }
1047
1048    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1049    // And an `X-HTTP-Method-Override` header.
1050    if (Backbone.emulateHTTP) {
1051      if (type === 'PUT' || type === 'DELETE') {
1052        if (Backbone.emulateJSON) params.data._method = type;
1053        params.type = 'POST';
1054        params.beforeSend = function(xhr) {
1055          xhr.setRequestHeader('X-HTTP-Method-Override', type);
1056        };
1057      }
1058    }
1059
1060    // Don't process data on a non-GET request.
1061    if (params.type !== 'GET' && !Backbone.emulateJSON) {
1062      params.processData = false;
1063    }
1064
1065    // Make the request, allowing the user to override any Ajax options.
1066    return $.ajax(_.extend(params, options));
1067  };
1068
1069  // Helpers
1070  // -------
1071
1072  // Shared empty constructor function to aid in prototype-chain creation.
1073  var ctor = function(){};
1074
1075  // Helper function to correctly set up the prototype chain, for subclasses.
1076  // Similar to `goog.inherits`, but uses a hash of prototype properties and
1077  // class properties to be extended.
1078  var inherits = function(parent, protoProps, staticProps) {
1079    var child;
1080
1081    // The constructor function for the new subclass is either defined by you
1082    // (the "constructor" property in your `extend` definition), or defaulted
1083    // by us to simply call `super()`.
1084    if (protoProps && protoProps.hasOwnProperty('constructor')) {
1085      child = protoProps.constructor;
1086    } else {
1087      child = function(){ return parent.apply(this, arguments); };
1088    }
1089
1090    // Inherit class (static) properties from parent.
1091    _.extend(child, parent);
1092
1093    // Set the prototype chain to inherit from `parent`, without calling
1094    // `parent`'s constructor function.
1095    ctor.prototype = parent.prototype;
1096    child.prototype = new ctor();
1097
1098    // Add prototype properties (instance properties) to the subclass,
1099    // if supplied.
1100    if (protoProps) _.extend(child.prototype, protoProps);
1101
1102    // Add static properties to the constructor function, if supplied.
1103    if (staticProps) _.extend(child, staticProps);
1104
1105    // Correctly set child's `prototype.constructor`.
1106    child.prototype.constructor = child;
1107
1108    // Set a convenience property in case the parent's prototype is needed later.
1109    child.__super__ = parent.prototype;
1110
1111    return child;
1112  };
1113
1114  // Helper function to get a value from a Backbone object as a property
1115  // or as a function.
1116  var getValue = function(object, prop) {
1117    if (!(object && object[prop])) return null;
1118    return _.isFunction(object[prop]) ? object[prop]() : object[prop];
1119  };
1120
1121  // Throw an error when a URL is needed, and none is supplied.
1122  var urlError = function() {
1123    throw new Error('A "url" property or function must be specified');
1124  };
1125
1126  // Wrap an optional error callback with a fallback error event.
1127  var wrapError = function(onError, originalModel, options) {
1128    return function(model, resp) {
1129      var resp = model === originalModel ? resp : model;
1130      if (onError) {
1131        onError(model, resp, options);
1132      } else {
1133        originalModel.trigger('error', model, resp, options);
1134      }
1135    };
1136  };
1137
1138  return Backbone;
1139}));