PageRenderTime 62ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/media/static/js/backbone.js

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