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

/js/lib/backbone.js

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