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

/src/PluginTestBed/Content/js/backbone-0.5.0.js

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