PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/priv/static/js/backbone.js

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