PageRenderTime 75ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/backbonejs/0.9.2/backbone.orig.js

http://github.com/thomasfr/requirified
JavaScript | 1431 lines | 856 code | 199 blank | 376 comment | 295 complexity | a959af924d21c7b788fe197caf03fc40 MD5 | raw file
Possible License(s): MIT, Apache-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file