PageRenderTime 70ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/practicals/modular-mobile-app/app/libs/AMDbackbone-0.5.3.js

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