PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/vendor/backbone.js

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