PageRenderTime 90ms CodeModel.GetById 26ms RepoModel.GetById 2ms app.codeStats 0ms

/learn.tddjs/code/test_deps/backbone.js

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