PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/app/web-app/js/backbone.js

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