PageRenderTime 66ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/public/javascripts/backbone.js

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