PageRenderTime 103ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

/pancake-web/pancake/web/static/js/vendor/backbone.js

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