PageRenderTime 53ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/public/libs/backbone.js

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