PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/Backbone/js/libs/backbone.js

https://bitbucket.org/ZachStowell/autolog
JavaScript | 1158 lines | 701 code | 154 blank | 303 comment | 243 complexity | 9426a20a63febc61fdad26aa72093253 MD5 | raw file
Possible License(s): Apache-2.0
  1. // Backbone.js 0.5.3
  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.3';
  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 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, context) {
  58. var calls = this._callbacks || (this._callbacks = {});
  59. var list = calls[ev] || (calls[ev] = []);
  60. list.push([callback, context]);
  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 (list[i] && callback === list[i][0]) {
  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[0].apply(callback[1] || 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.call(this);
  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);
  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', 'groupBy'];
  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 decodeURIComponent(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. // Return immediately as browser will do redirect to new url
  705. return true;
  706. } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
  707. this.fragment = loc.hash.replace(hashStrip, '');
  708. window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
  709. }
  710. if (!this.options.silent) {
  711. return this.loadUrl();
  712. }
  713. },
  714. // Add a route to be tested when the fragment changes. Routes added later may
  715. // override previous routes.
  716. route : function(route, callback) {
  717. this.handlers.unshift({route : route, callback : callback});
  718. },
  719. // Checks the current URL to see if it has changed, and if it has,
  720. // calls `loadUrl`, normalizing across the hidden iframe.
  721. checkUrl : function(e) {
  722. var current = this.getFragment();
  723. if (current == this.fragment && this.iframe) current = this.getFragment(this.iframe.location.hash);
  724. if (current == this.fragment || current == decodeURIComponent(this.fragment)) return false;
  725. if (this.iframe) this.navigate(current);
  726. this.loadUrl() || this.loadUrl(window.location.hash);
  727. },
  728. // Attempt to load the current URL fragment. If a route succeeds with a
  729. // match, returns `true`. If no defined routes matches the fragment,
  730. // returns `false`.
  731. loadUrl : function(fragmentOverride) {
  732. var fragment = this.fragment = this.getFragment(fragmentOverride);
  733. var matched = _.any(this.handlers, function(handler) {
  734. if (handler.route.test(fragment)) {
  735. handler.callback(fragment);
  736. return true;
  737. }
  738. });
  739. return matched;
  740. },
  741. // Save a fragment into the hash history. You are responsible for properly
  742. // URL-encoding the fragment in advance. This does not trigger
  743. // a `hashchange` event.
  744. navigate : function(fragment, triggerRoute) {
  745. var frag = (fragment || '').replace(hashStrip, '');
  746. if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return;
  747. if (this._hasPushState) {
  748. var loc = window.location;
  749. if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
  750. this.fragment = frag;
  751. window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + frag);
  752. } else {
  753. window.location.hash = this.fragment = frag;
  754. if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) {
  755. this.iframe.document.open().close();
  756. this.iframe.location.hash = frag;
  757. }
  758. }
  759. if (triggerRoute) this.loadUrl(fragment);
  760. }
  761. });
  762. // Backbone.View
  763. // -------------
  764. // Creating a Backbone.View creates its initial element outside of the DOM,
  765. // if an existing element is not provided...
  766. Backbone.View = function(options) {
  767. this.cid = _.uniqueId('view');
  768. this._configure(options || {});
  769. this._ensureElement();
  770. this.delegateEvents();
  771. this.initialize.apply(this, arguments);
  772. };
  773. // Element lookup, scoped to DOM elements within the current view.
  774. // This should be prefered to global lookups, if you're dealing with
  775. // a specific view.
  776. var selectorDelegate = function(selector) {
  777. return $(selector, this.el);
  778. };
  779. // Cached regex to split keys for `delegate`.
  780. var eventSplitter = /^(\S+)\s*(.*)$/;
  781. // List of view options to be merged as properties.
  782. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
  783. // Set up all inheritable **Backbone.View** properties and methods.
  784. _.extend(Backbone.View.prototype, Backbone.Events, {
  785. // The default `tagName` of a View's element is `"div"`.
  786. tagName : 'div',
  787. // Attach the `selectorDelegate` function as the `$` property.
  788. $ : selectorDelegate,
  789. // Initialize is an empty function by default. Override it with your own
  790. // initialization logic.
  791. initialize : function(){},
  792. // **render** is the core function that your view should override, in order
  793. // to populate its element (`this.el`), with the appropriate HTML. The
  794. // convention is for **render** to always return `this`.
  795. render : function() {
  796. return this;
  797. },
  798. // Remove this view from the DOM. Note that the view isn't present in the
  799. // DOM by default, so calling this method may be a no-op.
  800. remove : function() {
  801. $(this.el).remove();
  802. return this;
  803. },
  804. // For small amounts of DOM Elements, where a full-blown template isn't
  805. // needed, use **make** to manufacture elements, one at a time.
  806. //
  807. // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
  808. //
  809. make : function(tagName, attributes, content) {
  810. var el = document.createElement(tagName);
  811. if (attributes) $(el).attr(attributes);
  812. if (content) $(el).html(content);
  813. return el;
  814. },
  815. // Set callbacks, where `this.callbacks` is a hash of
  816. //
  817. // *{"event selector": "callback"}*
  818. //
  819. // {
  820. // 'mousedown .title': 'edit',
  821. // 'click .button': 'save'
  822. // }
  823. //
  824. // pairs. Callbacks will be bound to the view, with `this` set properly.
  825. // Uses event delegation for efficiency.
  826. // Omitting the selector binds the event to `this.el`.
  827. // This only works for delegate-able events: not `focus`, `blur`, and
  828. // not `change`, `submit`, and `reset` in Internet Explorer.
  829. delegateEvents : function(events) {
  830. if (!(events || (events = this.events))) return;
  831. if (_.isFunction(events)) events = events.call(this);
  832. $(this.el).unbind('.delegateEvents' + this.cid);
  833. for (var key in events) {
  834. var method = this[events[key]];
  835. if (!method) throw new Error('Event "' + events[key] + '" does not exist');
  836. var match = key.match(eventSplitter);
  837. var eventName = match[1], selector = match[2];
  838. method = _.bind(method, this);
  839. eventName += '.delegateEvents' + this.cid;
  840. if (selector === '') {
  841. $(this.el).bind(eventName, method);
  842. } else {
  843. $(this.el).delegate(selector, eventName, method);
  844. }
  845. }
  846. },
  847. // Performs the initial configuration of a View with a set of options.
  848. // Keys with special meaning *(model, collection, id, className)*, are
  849. // attached directly to the view.
  850. _configure : function(options) {
  851. if (this.options) options = _.extend({}, this.options, options);
  852. for (var i = 0, l = viewOptions.length; i < l; i++) {
  853. var attr = viewOptions[i];
  854. if (options[attr]) this[attr] = options[attr];
  855. }
  856. this.options = options;
  857. },
  858. // Ensure that the View has a DOM element to render into.
  859. // If `this.el` is a string, pass it through `$()`, take the first
  860. // matching element, and re-assign it to `el`. Otherwise, create
  861. // an element from the `id`, `className` and `tagName` proeprties.
  862. _ensureElement : function() {
  863. if (!this.el) {
  864. var attrs = this.attributes || {};
  865. if (this.id) attrs.id = this.id;
  866. if (this.className) attrs['class'] = this.className;
  867. this.el = this.make(this.tagName, attrs);
  868. } else if (_.isString(this.el)) {
  869. this.el = $(this.el).get(0);
  870. }
  871. }
  872. });
  873. // The self-propagating extend function that Backbone classes use.
  874. var extend = function (protoProps, classProps) {
  875. var child = inherits(this, protoProps, classProps);
  876. child.extend = this.extend;
  877. return child;
  878. };
  879. // Set up inheritance for the model, collection, and view.
  880. Backbone.Model.extend = Backbone.Collection.extend =
  881. Backbone.Router.extend = Backbone.View.extend = extend;
  882. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  883. var methodMap = {
  884. 'create': 'POST',
  885. 'update': 'PUT',
  886. 'delete': 'DELETE',
  887. 'read' : 'GET'
  888. };
  889. // Backbone.sync
  890. // -------------
  891. // Override this function to change the manner in which Backbone persists
  892. // models to the server. You will be passed the type of request, and the
  893. // model in question. By default, uses makes a RESTful Ajax request
  894. // to the model's `url()`. Some possible customizations could be:
  895. //
  896. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  897. // * Send up the models as XML instead of JSON.
  898. // * Persist models via WebSockets instead of Ajax.
  899. //
  900. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  901. // as `POST`, with a `_method` parameter containing the true HTTP method,
  902. // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
  903. // `application/json` with the model in a param named `model`.
  904. // Useful when interfacing with server-side languages like **PHP** that make
  905. // it difficult to read the body of `PUT` requests.
  906. Backbone.sync = function(method, model, options) {
  907. var type = methodMap[method];
  908. // Default JSON-request options.
  909. var params = _.extend({
  910. type: type,
  911. dataType: 'json'
  912. }, options);
  913. // Ensure that we have a URL.
  914. if (!params.url) {
  915. params.url = getUrl(model) || urlError();
  916. }
  917. // Ensure that we have the appropriate request data.
  918. if (!params.data && model && (method == 'create' || method == 'update')) {
  919. params.contentType = 'application/json';
  920. params.data = JSON.stringify(model.toJSON());
  921. }
  922. // For older servers, emulate JSON by encoding the request into an HTML-form.
  923. if (Backbone.emulateJSON) {
  924. params.contentType = 'application/x-www-form-urlencoded';
  925. params.data = params.data ? {model : params.data} : {};
  926. }
  927. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  928. // And an `X-HTTP-Method-Override` header.
  929. if (Backbone.emulateHTTP) {
  930. if (type === 'PUT' || type === 'DELETE') {
  931. if (Backbone.emulateJSON) params.data._method = type;
  932. params.type = 'POST';
  933. params.beforeSend = function(xhr) {
  934. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  935. };
  936. }
  937. }
  938. // Don't process data on a non-GET request.
  939. if (params.type !== 'GET' && !Backbone.emulateJSON) {
  940. params.processData = false;
  941. }
  942. // Make the request.
  943. return $.ajax(params);
  944. };
  945. // Helpers
  946. // -------
  947. // Shared empty constructor function to aid in prototype-chain creation.
  948. var ctor = function(){};
  949. // Helper function to correctly set up the prototype chain, for subclasses.
  950. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  951. // class properties to be extended.
  952. var inherits = function(parent, protoProps, staticProps) {
  953. var child;
  954. // The constructor function for the new subclass is either defined by you
  955. // (the "constructor" property in your `extend` definition), or defaulted
  956. // by us to simply call `super()`.
  957. if (protoProps && protoProps.hasOwnProperty('constructor')) {
  958. child = protoProps.constructor;
  959. } else {
  960. child = function(){ return parent.apply(this, arguments); };
  961. }
  962. // Inherit class (static) properties from parent.
  963. _.extend(child, parent);
  964. // Set the prototype chain to inherit from `parent`, without calling
  965. // `parent`'s constructor function.
  966. ctor.prototype = parent.prototype;
  967. child.prototype = new ctor();
  968. // Add prototype properties (instance properties) to the subclass,
  969. // if supplied.
  970. if (protoProps) _.extend(child.prototype, protoProps);
  971. // Add static properties to the constructor function, if supplied.
  972. if (staticProps) _.extend(child, staticProps);
  973. // Correctly set child's `prototype.constructor`.
  974. child.prototype.constructor = child;
  975. // Set a convenience property in case the parent's prototype is needed later.
  976. child.__super__ = parent.prototype;
  977. return child;
  978. };
  979. // Helper function to get a URL from a Model or Collection as a property
  980. // or as a function.
  981. var getUrl = function(object) {
  982. if (!(object && object.url)) return null;
  983. return _.isFunction(object.url) ? object.url() : object.url;
  984. };
  985. // Throw an error when a URL is needed, and none is supplied.
  986. var urlError = function() {
  987. throw new Error('A "url" property or function must be specified');
  988. };
  989. // Wrap an optional error callback with a fallback error event.
  990. var wrapError = function(onError, model, options) {
  991. return function(resp) {
  992. if (onError) {
  993. onError(model, resp, options);
  994. } else {
  995. model.trigger('error', model, resp, options);
  996. }
  997. };
  998. };
  999. // Helper function to escape a string for HTML rendering.
  1000. var escapeHTML = function(string) {
  1001. 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;');
  1002. };
  1003. }).call(this);