PageRenderTime 62ms CodeModel.GetById 15ms app.highlight 38ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/assets/javascripts/backbone.js

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