PageRenderTime 75ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/9-final/public/js/vendor/backbone.js

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