PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/example/lib/backbone.js

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