PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/option4_grails_mongo/web-app/backbone.js

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