PageRenderTime 91ms CodeModel.GetById 3ms app.highlight 77ms RepoModel.GetById 1ms app.codeStats 0ms

/test/fixtures/json2_backbone.js

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