/www/protected/extensions/admin/assets/js/libs/backbone/0.5.3-optamd3/backbone.js

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