PageRenderTime 63ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/media/js/vendors/backbone.js

https://bitbucket.org/semion/busido
JavaScript | 1571 lines | 929 code | 224 blank | 418 comment | 308 complexity | 1adb34b904b20cb1823f4174e5b69d40 MD5 | raw file

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

  1. // Backbone.js 1.0.0
  2. // (c) 2010-2013 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, `exports`
  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 local references to array methods we'll want to use later.
  16. var array = [];
  17. var push = array.push;
  18. var slice = array.slice;
  19. var splice = array.splice;
  20. // The top-level namespace. All public Backbone classes and modules will
  21. // be attached to this. Exported for both the browser and the server.
  22. var Backbone;
  23. if (typeof exports !== 'undefined') {
  24. Backbone = exports;
  25. } else {
  26. Backbone = root.Backbone = {};
  27. }
  28. // Current version of the library. Keep in sync with `package.json`.
  29. Backbone.VERSION = '1.0.0';
  30. // Require Underscore, if we're on the server, and it's not already present.
  31. var _ = root._;
  32. if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
  33. // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
  34. // the `$` variable.
  35. Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
  36. // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  37. // to its previous owner. Returns a reference to this Backbone object.
  38. Backbone.noConflict = function() {
  39. root.Backbone = previousBackbone;
  40. return this;
  41. };
  42. // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  43. // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  44. // set a `X-Http-Method-Override` header.
  45. Backbone.emulateHTTP = false;
  46. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  47. // `application/json` requests ... will encode the body as
  48. // `application/x-www-form-urlencoded` instead and will send the model in a
  49. // form param named `model`.
  50. Backbone.emulateJSON = false;
  51. // Backbone.Events
  52. // ---------------
  53. // A module that can be mixed in to *any object* in order to provide it with
  54. // custom events. You may bind with `on` or remove with `off` callback
  55. // functions to an event; `trigger`-ing an event fires all callbacks in
  56. // succession.
  57. //
  58. // var object = {};
  59. // _.extend(object, Backbone.Events);
  60. // object.on('expand', function(){ alert('expanded'); });
  61. // object.trigger('expand');
  62. //
  63. var Events = Backbone.Events = {
  64. // Bind an event to a `callback` function. Passing `"all"` will bind
  65. // the callback to all events fired.
  66. on: function(name, callback, context) {
  67. if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
  68. this._events || (this._events = {});
  69. var events = this._events[name] || (this._events[name] = []);
  70. events.push({callback: callback, context: context, ctx: context || this});
  71. return this;
  72. },
  73. // Bind an event to only be triggered a single time. After the first time
  74. // the callback is invoked, it will be removed.
  75. once: function(name, callback, context) {
  76. if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
  77. var self = this;
  78. var once = _.once(function() {
  79. self.off(name, once);
  80. callback.apply(this, arguments);
  81. });
  82. once._callback = callback;
  83. return this.on(name, once, context);
  84. },
  85. // Remove one or many callbacks. If `context` is null, removes all
  86. // callbacks with that function. If `callback` is null, removes all
  87. // callbacks for the event. If `name` is null, removes all bound
  88. // callbacks for all events.
  89. off: function(name, callback, context) {
  90. var retain, ev, events, names, i, l, j, k;
  91. if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
  92. if (!name && !callback && !context) {
  93. this._events = {};
  94. return this;
  95. }
  96. names = name ? [name] : _.keys(this._events);
  97. for (i = 0, l = names.length; i < l; i++) {
  98. name = names[i];
  99. if (events = this._events[name]) {
  100. this._events[name] = retain = [];
  101. if (callback || context) {
  102. for (j = 0, k = events.length; j < k; j++) {
  103. ev = events[j];
  104. if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
  105. (context && context !== ev.context)) {
  106. retain.push(ev);
  107. }
  108. }
  109. }
  110. if (!retain.length) delete this._events[name];
  111. }
  112. }
  113. return this;
  114. },
  115. // Trigger one or many events, firing all bound callbacks. Callbacks are
  116. // passed the same arguments as `trigger` is, apart from the event name
  117. // (unless you're listening on `"all"`, which will cause your callback to
  118. // receive the true name of the event as the first argument).
  119. trigger: function(name) {
  120. if (!this._events) return this;
  121. var args = slice.call(arguments, 1);
  122. if (!eventsApi(this, 'trigger', name, args)) return this;
  123. var events = this._events[name];
  124. var allEvents = this._events.all;
  125. if (events) triggerEvents(events, args);
  126. if (allEvents) triggerEvents(allEvents, arguments);
  127. return this;
  128. },
  129. // Tell this object to stop listening to either specific events ... or
  130. // to every object it's currently listening to.
  131. stopListening: function(obj, name, callback) {
  132. var listeners = this._listeners;
  133. if (!listeners) return this;
  134. var deleteListener = !name && !callback;
  135. if (typeof name === 'object') callback = this;
  136. if (obj) (listeners = {})[obj._listenerId] = obj;
  137. for (var id in listeners) {
  138. listeners[id].off(name, callback, this);
  139. if (deleteListener) delete this._listeners[id];
  140. }
  141. return this;
  142. }
  143. };
  144. // Regular expression used to split event strings.
  145. var eventSplitter = /\s+/;
  146. // Implement fancy features of the Events API such as multiple event
  147. // names `"change blur"` and jQuery-style event maps `{change: action}`
  148. // in terms of the existing API.
  149. var eventsApi = function(obj, action, name, rest) {
  150. if (!name) return true;
  151. // Handle event maps.
  152. if (typeof name === 'object') {
  153. for (var key in name) {
  154. obj[action].apply(obj, [key, name[key]].concat(rest));
  155. }
  156. return false;
  157. }
  158. // Handle space separated event names.
  159. if (eventSplitter.test(name)) {
  160. var names = name.split(eventSplitter);
  161. for (var i = 0, l = names.length; i < l; i++) {
  162. obj[action].apply(obj, [names[i]].concat(rest));
  163. }
  164. return false;
  165. }
  166. return true;
  167. };
  168. // A difficult-to-believe, but optimized internal dispatch function for
  169. // triggering events. Tries to keep the usual cases speedy (most internal
  170. // Backbone events have 3 arguments).
  171. var triggerEvents = function(events, args) {
  172. var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
  173. switch (args.length) {
  174. case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
  175. case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
  176. case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
  177. case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
  178. default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
  179. }
  180. };
  181. var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
  182. // Inversion-of-control versions of `on` and `once`. Tell *this* object to
  183. // listen to an event in another object ... keeping track of what it's
  184. // listening to.
  185. _.each(listenMethods, function(implementation, method) {
  186. Events[method] = function(obj, name, callback) {
  187. var listeners = this._listeners || (this._listeners = {});
  188. var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
  189. listeners[id] = obj;
  190. if (typeof name === 'object') callback = this;
  191. obj[implementation](name, callback, this);
  192. return this;
  193. };
  194. });
  195. // Aliases for backwards compatibility.
  196. Events.bind = Events.on;
  197. Events.unbind = Events.off;
  198. // Allow the `Backbone` object to serve as a global event bus, for folks who
  199. // want global "pubsub" in a convenient place.
  200. _.extend(Backbone, Events);
  201. // Backbone.Model
  202. // --------------
  203. // Backbone **Models** are the basic data object in the framework --
  204. // frequently representing a row in a table in a database on your server.
  205. // A discrete chunk of data and a bunch of useful, related methods for
  206. // performing computations and transformations on that data.
  207. // Create a new model with the specified attributes. A client id (`cid`)
  208. // is automatically generated and assigned for you.
  209. var Model = Backbone.Model = function(attributes, options) {
  210. var defaults;
  211. var attrs = attributes || {};
  212. options || (options = {});
  213. this.cid = _.uniqueId('c');
  214. this.attributes = {};
  215. _.extend(this, _.pick(options, modelOptions));
  216. if (options.parse) attrs = this.parse(attrs, options) || {};
  217. if (defaults = _.result(this, 'defaults')) {
  218. attrs = _.defaults({}, attrs, defaults);
  219. }
  220. this.set(attrs, options);
  221. this.changed = {};
  222. this.initialize.apply(this, arguments);
  223. };
  224. // A list of options to be attached directly to the model, if provided.
  225. var modelOptions = ['url', 'urlRoot', 'collection'];
  226. // Attach all inheritable methods to the Model prototype.
  227. _.extend(Model.prototype, Events, {
  228. // A hash of attributes whose current and previous value differ.
  229. changed: null,
  230. // The value returned during the last failed validation.
  231. validationError: null,
  232. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  233. // CouchDB users may want to set this to `"_id"`.
  234. idAttribute: 'id',
  235. // Initialize is an empty function by default. Override it with your own
  236. // initialization logic.
  237. initialize: function(){},
  238. // Return a copy of the model's `attributes` object.
  239. toJSON: function(options) {
  240. return _.clone(this.attributes);
  241. },
  242. // Proxy `Backbone.sync` by default -- but override this if you need
  243. // custom syncing semantics for *this* particular model.
  244. sync: function() {
  245. return Backbone.sync.apply(this, arguments);
  246. },
  247. // Get the value of an attribute.
  248. get: function(attr) {
  249. return this.attributes[attr];
  250. },
  251. // Get the HTML-escaped value of an attribute.
  252. escape: function(attr) {
  253. return _.escape(this.get(attr));
  254. },
  255. // Returns `true` if the attribute contains a value that is not null
  256. // or undefined.
  257. has: function(attr) {
  258. return this.get(attr) != null;
  259. },
  260. // Set a hash of model attributes on the object, firing `"change"`. This is
  261. // the core primitive operation of a model, updating the data and notifying
  262. // anyone who needs to know about the change in state. The heart of the beast.
  263. set: function(key, val, options) {
  264. var attr, attrs, unset, changes, silent, changing, prev, current;
  265. if (key == null) return this;
  266. // Handle both `"key", value` and `{key: value}` -style arguments.
  267. if (typeof key === 'object') {
  268. attrs = key;
  269. options = val;
  270. } else {
  271. (attrs = {})[key] = val;
  272. }
  273. options || (options = {});
  274. // Run validation.
  275. if (!this._validate(attrs, options)) return false;
  276. // Extract attributes and options.
  277. unset = options.unset;
  278. silent = options.silent;
  279. changes = [];
  280. changing = this._changing;
  281. this._changing = true;
  282. if (!changing) {
  283. this._previousAttributes = _.clone(this.attributes);
  284. this.changed = {};
  285. }
  286. current = this.attributes, prev = this._previousAttributes;
  287. // Check for changes of `id`.
  288. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
  289. // For each `set` attribute, update or delete the current value.
  290. for (attr in attrs) {
  291. val = attrs[attr];
  292. if (!_.isEqual(current[attr], val)) changes.push(attr);
  293. if (!_.isEqual(prev[attr], val)) {
  294. this.changed[attr] = val;
  295. } else {
  296. delete this.changed[attr];
  297. }
  298. unset ? delete current[attr] : current[attr] = val;
  299. }
  300. // Trigger all relevant attribute changes.
  301. if (!silent) {
  302. if (changes.length) this._pending = true;
  303. for (var i = 0, l = changes.length; i < l; i++) {
  304. this.trigger('change:' + changes[i], this, current[changes[i]], options);
  305. }
  306. }
  307. // You might be wondering why there's a `while` loop here. Changes can
  308. // be recursively nested within `"change"` events.
  309. if (changing) return this;
  310. if (!silent) {
  311. while (this._pending) {
  312. this._pending = false;
  313. this.trigger('change', this, options);
  314. }
  315. }
  316. this._pending = false;
  317. this._changing = false;
  318. return this;
  319. },
  320. // Remove an attribute from the model, firing `"change"`. `unset` is a noop
  321. // if the attribute doesn't exist.
  322. unset: function(attr, options) {
  323. return this.set(attr, void 0, _.extend({}, options, {unset: true}));
  324. },
  325. // Clear all attributes on the model, firing `"change"`.
  326. clear: function(options) {
  327. var attrs = {};
  328. for (var key in this.attributes) attrs[key] = void 0;
  329. return this.set(attrs, _.extend({}, options, {unset: true}));
  330. },
  331. // Determine if the model has changed since the last `"change"` event.
  332. // If you specify an attribute name, determine if that attribute has changed.
  333. hasChanged: function(attr) {
  334. if (attr == null) return !_.isEmpty(this.changed);
  335. return _.has(this.changed, attr);
  336. },
  337. // Return an object containing all the attributes that have changed, or
  338. // false if there are no changed attributes. Useful for determining what
  339. // parts of a view need to be updated and/or what attributes need to be
  340. // persisted to the server. Unset attributes will be set to undefined.
  341. // You can also pass an attributes object to diff against the model,
  342. // determining if there *would be* a change.
  343. changedAttributes: function(diff) {
  344. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  345. var val, changed = false;
  346. var old = this._changing ? this._previousAttributes : this.attributes;
  347. for (var attr in diff) {
  348. if (_.isEqual(old[attr], (val = diff[attr]))) continue;
  349. (changed || (changed = {}))[attr] = val;
  350. }
  351. return changed;
  352. },
  353. // Get the previous value of an attribute, recorded at the time the last
  354. // `"change"` event was fired.
  355. previous: function(attr) {
  356. if (attr == null || !this._previousAttributes) return null;
  357. return this._previousAttributes[attr];
  358. },
  359. // Get all of the attributes of the model at the time of the previous
  360. // `"change"` event.
  361. previousAttributes: function() {
  362. return _.clone(this._previousAttributes);
  363. },
  364. // Fetch the model from the server. If the server's representation of the
  365. // model differs from its current attributes, they will be overridden,
  366. // triggering a `"change"` event.
  367. fetch: function(options) {
  368. options = options ? _.clone(options) : {};
  369. if (options.parse === void 0) options.parse = true;
  370. var model = this;
  371. var success = options.success;
  372. options.success = function(resp) {
  373. if (!model.set(model.parse(resp, options), options)) return false;
  374. if (success) success(model, resp, options);
  375. model.trigger('sync', model, resp, options);
  376. };
  377. wrapError(this, options);
  378. return this.sync('read', this, options);
  379. },
  380. // Set a hash of model attributes, and sync the model to the server.
  381. // If the server returns an attributes hash that differs, the model's
  382. // state will be `set` again.
  383. save: function(key, val, options) {
  384. var attrs, method, xhr, attributes = this.attributes;
  385. // Handle both `"key", value` and `{key: value}` -style arguments.
  386. if (key == null || typeof key === 'object') {
  387. attrs = key;
  388. options = val;
  389. } else {
  390. (attrs = {})[key] = val;
  391. }
  392. // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
  393. if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
  394. options = _.extend({validate: true}, options);
  395. // Do not persist invalid models.
  396. if (!this._validate(attrs, options)) return false;
  397. // Set temporary attributes if `{wait: true}`.
  398. if (attrs && options.wait) {
  399. this.attributes = _.extend({}, attributes, attrs);
  400. }
  401. // After a successful server-side save, the client is (optionally)
  402. // updated with the server-side state.
  403. if (options.parse === void 0) options.parse = true;
  404. var model = this;
  405. var success = options.success;
  406. options.success = function(resp) {
  407. // Ensure attributes are restored during synchronous saves.
  408. model.attributes = attributes;
  409. var serverAttrs = model.parse(resp, options);
  410. if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
  411. if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
  412. return false;
  413. }
  414. if (success) success(model, resp, options);
  415. model.trigger('sync', model, resp, options);
  416. };
  417. wrapError(this, options);
  418. method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
  419. if (method === 'patch') options.attrs = attrs;
  420. xhr = this.sync(method, this, options);
  421. // Restore attributes.
  422. if (attrs && options.wait) this.attributes = attributes;
  423. return xhr;
  424. },
  425. // Destroy this model on the server if it was already persisted.
  426. // Optimistically removes the model from its collection, if it has one.
  427. // If `wait: true` is passed, waits for the server to respond before removal.
  428. destroy: function(options) {
  429. options = options ? _.clone(options) : {};
  430. var model = this;
  431. var success = options.success;
  432. var destroy = function() {
  433. model.trigger('destroy', model, model.collection, options);
  434. };
  435. options.success = function(resp) {
  436. if (options.wait || model.isNew()) destroy();
  437. if (success) success(model, resp, options);
  438. if (!model.isNew()) model.trigger('sync', model, resp, options);
  439. };
  440. if (this.isNew()) {
  441. options.success();
  442. return false;
  443. }
  444. wrapError(this, options);
  445. var xhr = this.sync('delete', this, options);
  446. if (!options.wait) destroy();
  447. return xhr;
  448. },
  449. // Default URL for the model's representation on the server -- if you're
  450. // using Backbone's restful methods, override this to change the endpoint
  451. // that will be called.
  452. url: function() {
  453. var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
  454. if (this.isNew()) return base;
  455. return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
  456. },
  457. // **parse** converts a response into the hash of attributes to be `set` on
  458. // the model. The default implementation is just to pass the response along.
  459. parse: function(resp, options) {
  460. return resp;
  461. },
  462. // Create a new model with identical attributes to this one.
  463. clone: function() {
  464. return new this.constructor(this.attributes);
  465. },
  466. // A model is new if it has never been saved to the server, and lacks an id.
  467. isNew: function() {
  468. return this.id == null;
  469. },
  470. // Check if the model is currently in a valid state.
  471. isValid: function(options) {
  472. return this._validate({}, _.extend(options || {}, { validate: true }));
  473. },
  474. // Run validation against the next complete set of model attributes,
  475. // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
  476. _validate: function(attrs, options) {
  477. if (!options.validate || !this.validate) return true;
  478. attrs = _.extend({}, this.attributes, attrs);
  479. var error = this.validationError = this.validate(attrs, options) || null;
  480. if (!error) return true;
  481. this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
  482. return false;
  483. }
  484. });
  485. // Underscore methods that we want to implement on the Model.
  486. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
  487. // Mix in each Underscore method as a proxy to `Model#attributes`.
  488. _.each(modelMethods, function(method) {
  489. Model.prototype[method] = function() {
  490. var args = slice.call(arguments);
  491. args.unshift(this.attributes);
  492. return _[method].apply(_, args);
  493. };
  494. });
  495. // Backbone.Collection
  496. // -------------------
  497. // If models tend to represent a single row of data, a Backbone Collection is
  498. // more analagous to a table full of data ... or a small slice or page of that
  499. // table, or a collection of rows that belong together for a particular reason
  500. // -- all of the messages in this particular folder, all of the documents
  501. // belonging to this particular author, and so on. Collections maintain
  502. // indexes of their models, both in order, and for lookup by `id`.
  503. // Create a new **Collection**, perhaps to contain a specific type of `model`.
  504. // If a `comparator` is specified, the Collection will maintain
  505. // its models in sort order, as they're added and removed.
  506. var Collection = Backbone.Collection = function(models, options) {
  507. options || (options = {});
  508. if (options.url) this.url = options.url;
  509. if (options.model) this.model = options.model;
  510. if (options.comparator !== void 0) this.comparator = options.comparator;
  511. this._reset();
  512. this.initialize.apply(this, arguments);
  513. if (models) this.reset(models, _.extend({silent: true}, options));
  514. };
  515. // Default options for `Collection#set`.
  516. var setOptions = {add: true, remove: true, merge: true};
  517. var addOptions = {add: true, merge: false, remove: false};
  518. // Define the Collection's inheritable methods.
  519. _.extend(Collection.prototype, Events, {
  520. // The default model for a collection is just a **Backbone.Model**.
  521. // This should be overridden in most cases.
  522. model: Model,
  523. // Initialize is an empty function by default. Override it with your own
  524. // initialization logic.
  525. initialize: function(){},
  526. // The JSON representation of a Collection is an array of the
  527. // models' attributes.
  528. toJSON: function(options) {
  529. return this.map(function(model){ return model.toJSON(options); });
  530. },
  531. // Proxy `Backbone.sync` by default.
  532. sync: function() {
  533. return Backbone.sync.apply(this, arguments);
  534. },
  535. // Add a model, or list of models to the set.
  536. add: function(models, options) {
  537. return this.set(models, _.defaults(options || {}, addOptions));
  538. },
  539. // Remove a model, or a list of models from the set.
  540. remove: function(models, options) {
  541. models = _.isArray(models) ? models.slice() : [models];
  542. options || (options = {});
  543. var i, l, index, model;
  544. for (i = 0, l = models.length; i < l; i++) {
  545. model = this.get(models[i]);
  546. if (!model) continue;
  547. delete this._byId[model.id];
  548. delete this._byId[model.cid];
  549. index = this.indexOf(model);
  550. this.models.splice(index, 1);
  551. this.length--;
  552. if (!options.silent) {
  553. options.index = index;
  554. model.trigger('remove', model, this, options);
  555. }
  556. this._removeReference(model);
  557. }
  558. return this;
  559. },
  560. // Update a collection by `set`-ing a new list of models, adding new ones,
  561. // removing models that are no longer present, and merging models that
  562. // already exist in the collection, as necessary. Similar to **Model#set**,
  563. // the core operation for updating the data contained by the collection.
  564. set: function(models, options) {
  565. options = _.defaults(options || {}, setOptions);
  566. if (options.parse) models = this.parse(models, options);
  567. if (!_.isArray(models)) models = models ? [models] : [];
  568. var i, l, model, attrs, existing, sort;
  569. var at = options.at;
  570. var sortable = this.comparator && (at == null) && options.sort !== false;
  571. var sortAttr = _.isString(this.comparator) ? this.comparator : null;
  572. var toAdd = [], toRemove = [], modelMap = {};
  573. // Turn bare objects into model references, and prevent invalid models
  574. // from being added.
  575. for (i = 0, l = models.length; i < l; i++) {
  576. if (!(model = this._prepareModel(models[i], options))) continue;
  577. // If a duplicate is found, prevent it from being added and
  578. // optionally merge it into the existing model.
  579. if (existing = this.get(model)) {
  580. if (options.remove) modelMap[existing.cid] = true;
  581. if (options.merge) {
  582. existing.set(model.attributes, options);
  583. if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
  584. }
  585. // This is a new model, push it to the `toAdd` list.
  586. } else if (options.add) {
  587. toAdd.push(model);
  588. // Listen to added models' events, and index models for lookup by
  589. // `id` and by `cid`.
  590. model.on('all', this._onModelEvent, this);
  591. this._byId[model.cid] = model;
  592. if (model.id != null) this._byId[model.id] = model;
  593. }
  594. }
  595. // Remove nonexistent models if appropriate.
  596. if (options.remove) {
  597. for (i = 0, l = this.length; i < l; ++i) {
  598. if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
  599. }
  600. if (toRemove.length) this.remove(toRemove, options);
  601. }
  602. // See if sorting is needed, update `length` and splice in new models.
  603. if (toAdd.length) {
  604. if (sortable) sort = true;
  605. this.length += toAdd.length;
  606. if (at != null) {
  607. splice.apply(this.models, [at, 0].concat(toAdd));
  608. } else {
  609. push.apply(this.models, toAdd);
  610. }
  611. }
  612. // Silently sort the collection if appropriate.
  613. if (sort) this.sort({silent: true});
  614. if (options.silent) return this;
  615. // Trigger `add` events.
  616. for (i = 0, l = toAdd.length; i < l; i++) {
  617. (model = toAdd[i]).trigger('add', model, this, options);
  618. }
  619. // Trigger `sort` if the collection was sorted.
  620. if (sort) this.trigger('sort', this, options);
  621. return this;
  622. },
  623. // When you have more items than you want to add or remove individually,
  624. // you can reset the entire set with a new list of models, without firing
  625. // any granular `add` or `remove` events. Fires `reset` when finished.
  626. // Useful for bulk operations and optimizations.
  627. reset: function(models, options) {
  628. options || (options = {});
  629. for (var i = 0, l = this.models.length; i < l; i++) {
  630. this._removeReference(this.models[i]);
  631. }
  632. options.previousModels = this.models;
  633. this._reset();
  634. this.add(models, _.extend({silent: true}, options));
  635. if (!options.silent) this.trigger('reset', this, options);
  636. return this;
  637. },
  638. // Add a model to the end of the collection.
  639. push: function(model, options) {
  640. model = this._prepareModel(model, options);
  641. this.add(model, _.extend({at: this.length}, options));
  642. return model;
  643. },
  644. // Remove a model from the end of the collection.
  645. pop: function(options) {
  646. var model = this.at(this.length - 1);
  647. this.remove(model, options);
  648. return model;
  649. },
  650. // Add a model to the beginning of the collection.
  651. unshift: function(model, options) {
  652. model = this._prepareModel(model, options);
  653. this.add(model, _.extend({at: 0}, options));
  654. return model;
  655. },
  656. // Remove a model from the beginning of the collection.
  657. shift: function(options) {
  658. var model = this.at(0);
  659. this.remove(model, options);
  660. return model;
  661. },
  662. // Slice out a sub-array of models from the collection.
  663. slice: function(begin, end) {
  664. return this.models.slice(begin, end);
  665. },
  666. // Get a model from the set by id.
  667. get: function(obj) {
  668. if (obj == null) return void 0;
  669. return this._byId[obj.id != null ? obj.id : obj.cid || obj];
  670. },
  671. // Get the model at the given index.
  672. at: function(index) {
  673. return this.models[index];
  674. },
  675. // Return models with matching attributes. Useful for simple cases of
  676. // `filter`.
  677. where: function(attrs, first) {
  678. if (_.isEmpty(attrs)) return first ? void 0 : [];
  679. return this[first ? 'find' : 'filter'](function(model) {
  680. for (var key in attrs) {
  681. if (attrs[key] !== model.get(key)) return false;
  682. }
  683. return true;
  684. });
  685. },
  686. // Return the first model with matching attributes. Useful for simple cases
  687. // of `find`.
  688. findWhere: function(attrs) {
  689. return this.where(attrs, true);
  690. },
  691. // Force the collection to re-sort itself. You don't need to call this under
  692. // normal circumstances, as the set will maintain sort order as each item
  693. // is added.
  694. sort: function(options) {
  695. if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
  696. options || (options = {});
  697. // Run sort based on type of `comparator`.
  698. if (_.isString(this.comparator) || this.comparator.length === 1) {
  699. this.models = this.sortBy(this.comparator, this);
  700. } else {
  701. this.models.sort(_.bind(this.comparator, this));
  702. }
  703. if (!options.silent) this.trigger('sort', this, options);
  704. return this;
  705. },
  706. // Figure out the smallest index at which a model should be inserted so as
  707. // to maintain order.
  708. sortedIndex: function(model, value, context) {
  709. value || (value = this.comparator);
  710. var iterator = _.isFunction(value) ? value : function(model) {
  711. return model.get(value);
  712. };
  713. return _.sortedIndex(this.models, model, iterator, context);
  714. },
  715. // Pluck an attribute from each model in the collection.
  716. pluck: function(attr) {
  717. return _.invoke(this.models, 'get', attr);
  718. },
  719. // Fetch the default set of models for this collection, resetting the
  720. // collection when they arrive. If `reset: true` is passed, the response
  721. // data will be passed through the `reset` method instead of `set`.
  722. fetch: function(options) {
  723. options = options ? _.clone(options) : {};
  724. if (options.parse === void 0) options.parse = true;
  725. var success = options.success;
  726. var collection = this;
  727. options.success = function(resp) {
  728. var method = options.reset ? 'reset' : 'set';
  729. collection[method](resp, options);
  730. if (success) success(collection, resp, options);
  731. collection.trigger('sync', collection, resp, options);
  732. };
  733. wrapError(this, options);
  734. return this.sync('read', this, options);
  735. },
  736. // Create a new instance of a model in this collection. Add the model to the
  737. // collection immediately, unless `wait: true` is passed, in which case we
  738. // wait for the server to agree.
  739. create: function(model, options) {
  740. options = options ? _.clone(options) : {};
  741. if (!(model = this._prepareModel(model, options))) return false;
  742. if (!options.wait) this.add(model, options);
  743. var collection = this;
  744. var success = options.success;
  745. options.success = function(resp) {
  746. if (options.wait) collection.add(model, options);
  747. if (success) success(model, resp, options);
  748. };
  749. model.save(null, options);
  750. return model;
  751. },
  752. // **parse** converts a response into a list of models to be added to the
  753. // collection. The default implementation is just to pass it through.
  754. parse: function(resp, options) {
  755. return resp;
  756. },
  757. // Create a new collection with an identical list of models as this one.
  758. clone: function() {
  759. return new this.constructor(this.models);
  760. },
  761. // Private method to reset all internal state. Called when the collection
  762. // is first initialized or reset.
  763. _reset: function() {
  764. this.length = 0;
  765. this.models = [];
  766. this._byId = {};
  767. },
  768. // Prepare a hash of attributes (or other model) to be added to this
  769. // collection.
  770. _prepareModel: function(attrs, options) {
  771. if (attrs instanceof Model) {
  772. if (!attrs.collection) attrs.collection = this;
  773. return attrs;
  774. }
  775. options || (options = {});
  776. options.collection = this;
  777. var model = new this.model(attrs, options);
  778. if (!model._validate(attrs, options)) {
  779. this.trigger('invalid', this, attrs, options);
  780. return false;
  781. }
  782. return model;
  783. },
  784. // Internal method to sever a model's ties to a collection.
  785. _removeReference: function(model) {
  786. if (this === model.collection) delete model.collection;
  787. model.off('all', this._onModelEvent, this);
  788. },
  789. // Internal method called every time a model in the set fires an event.
  790. // Sets need to update their indexes when models change ids. All other
  791. // events simply proxy through. "add" and "remove" events that originate
  792. // in other collections are ignored.
  793. _onModelEvent: function(event, model, collection, options) {
  794. if ((event === 'add' || event === 'remove') && collection !== this) return;
  795. if (event === 'destroy') this.remove(model, options);
  796. if (model && event === 'change:' + model.idAttribute) {
  797. delete this._byId[model.previous(model.idAttribute)];
  798. if (model.id != null) this._byId[model.id] = model;
  799. }
  800. this.trigger.apply(this, arguments);
  801. }
  802. });
  803. // Underscore methods that we want to implement on the Collection.
  804. // 90% of the core usefulness of Backbone Collections is actually implemented
  805. // right here:
  806. var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
  807. 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
  808. 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
  809. 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
  810. 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
  811. 'isEmpty', 'chain'];
  812. // Mix in each Underscore method as a proxy to `Collection#models`.
  813. _.each(methods, function(method) {
  814. Collection.prototype[method] = function() {
  815. var args = slice.call(arguments);
  816. args.unshift(this.models);
  817. return _[method].apply(_, args);
  818. };
  819. });
  820. // Underscore methods that take a property name as an argument.
  821. var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
  822. // Use attributes instead of properties.
  823. _.each(attributeMethods, function(method) {
  824. Collection.prototype[method] = function(value, context) {
  825. var iterator = _.isFunction(value) ? value : function(model) {
  826. return model.get(value);
  827. };
  828. return _[method](this.models, iterator, context);
  829. };
  830. });
  831. // Backbone.View
  832. // -------------
  833. // Backbone Views are almost more convention than they are actual code. A View
  834. // is simply a JavaScript object that represents a logical chunk of UI in the
  835. // DOM. This might be a single item, an entire list, a sidebar or panel, or
  836. // even the surrounding frame which wraps your whole app. Defining a chunk of
  837. // UI as a **View** allows you to define your DOM events declaratively, without
  838. // having to worry about render order ... and makes it easy for the view to
  839. // react to specific changes in the state of your models.
  840. // Creating a Backbone.View creates its initial element outside of the DOM,
  841. // if an existing element is not provided...
  842. var View = Backbone.View = function(options) {
  843. this.cid = _.uniqueId('view');
  844. this._configure(options || {});
  845. this._ensureElement();
  846. this.initialize.apply(this, arguments);
  847. this.delegateEvents();
  848. };
  849. // Cached regex to split keys for `delegate`.
  850. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  851. // List of view options to be merged as properties.
  852. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
  853. // Set up all inheritable **Backbone.View** properties and methods.
  854. _.extend(View.prototype, Events, {
  855. // The default `tagName` of a View's element is `"div"`.
  856. tagName: 'div',
  857. // jQuery delegate for element lookup, scoped to DOM elements within the
  858. // current view. This should be prefered to global lookups where possible.
  859. $: function(selector) {
  860. return this.$el.find(selector);
  861. },
  862. // Initialize is an empty function by default. Override it with your own
  863. // initialization logic.
  864. initialize: function(){},
  865. // **render** is the core function that your view should override, in order
  866. // to populate its element (`this.el`), with the appropriate HTML. The
  867. // convention is for **render** to always return `this`.
  868. render: function() {
  869. return this;
  870. },
  871. // Remove this view by taking the element out of the DOM, and removing any
  872. // applicable Backbone.Events listeners.
  873. remove: function() {
  874. this.$el.remove();
  875. this.stopListening();
  876. return this;
  877. },
  878. // Change the view's element (`this.el` property), including event
  879. // re-delegation.
  880. setElement: function(element, delegate) {
  881. if (this.$el) this.undelegateEvents();
  882. this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
  883. this.el = this.$el[0];
  884. if (delegate !== false) this.delegateEvents();
  885. return this;
  886. },
  887. // Set callbacks, where `this.events` is a hash of
  888. //
  889. // *{"event selector": "callback"}*
  890. //
  891. // {
  892. // 'mousedown .title': 'edit',
  893. // 'click .button': 'save'
  894. // 'click .open': function(e) { ... }
  895. // }
  896. //
  897. // pairs. Callbacks will be bound to the view, with `this` set properly.
  898. // Uses event delegation for efficiency.
  899. // Omitting the selector binds the event to `this.el`.
  900. // This only works for delegate-able events: not `focus`, `blur`, and
  901. // not `change`, `submit`, and `reset` in Internet Explorer.
  902. delegateEvents: function(events) {
  903. if (!(events || (events = _.result(this, 'events')))) return this;
  904. this.undelegateEvents();
  905. for (var key in events) {
  906. var method = events[key];
  907. if (!_.isFunction(method)) method = this[events[key]];
  908. if (!method) continue;
  909. var match = key.match(delegateEventSplitter);
  910. var eventName = match[1], selector = match[2];
  911. method = _.bind(method, this);
  912. eventName += '.delegateEvents' + this.cid;
  913. if (selector === '') {
  914. this.$el.on(eventName, method);
  915. } else {
  916. this.$el.on(eventName, selector, method);
  917. }
  918. }
  919. return this;
  920. },
  921. // Clears all callbacks previously bound to the view with `delegateEvents`.
  922. // You usually don't need to use this, but may wish to if you have multiple
  923. // Backbone views attached to the same DOM element.
  924. undelegateEvents: function() {
  925. this.$el.off('.delegateEvents' + this.cid);
  926. return this;
  927. },
  928. // Performs the initial configuration of a View with a set of options.
  929. // Keys with special meaning *(e.g. model, collection, id, className)* are
  930. // attached directly to the view. See `viewOptions` for an exhaustive
  931. // list.
  932. _configure: function(options) {
  933. if (this.options) options = _.extend({}, _.result(this, 'options'), options);
  934. _.extend(this, _.pick(options, viewOptions));
  935. this.options = options;
  936. },
  937. // Ensure that the View has a DOM element to render into.
  938. // If `this.el` is a string, pass it through `$()`, take the first
  939. // matching element, and re-assign it to `el`. Otherwise, create
  940. // an element from the `id`, `className` and `tagName` properties.
  941. _ensureElement: function() {
  942. if (!this.el) {
  943. var attrs = _.extend({}, _.result(this, 'attributes'));
  944. if (this.id) attrs.id = _.result(this, 'id');
  945. if (this.className) attrs['class'] = _.result(this, 'className');
  946. var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
  947. this.setElement($el, false);
  948. } else {
  949. this.setElement(_.result(this, 'el'), false);
  950. }
  951. }
  952. });
  953. // Backbone.sync
  954. // -------------
  955. // Override this function to change the manner in which Backbone persists
  956. // models to the server. You will be passed the type of request, and the
  957. // model in question. By default, makes a RESTful Ajax request
  958. // to the model's `url()`. Some possible customizations could be:
  959. //
  960. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  961. // * Send up the models as XML instead of JSON.
  962. // * Persist models via WebSockets instead of Ajax.
  963. //
  964. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  965. // as `POST`, with a `_method` parameter containing the true HTTP method,
  966. // as well as all requests with the body as `application/x-www-form-urlencoded`
  967. // instead of `application/json` with the model in a param named `model`.
  968. // Useful when interfacing with server-side languages like **PHP** that make
  969. // it difficult to read the body of `PUT` requests.
  970. Backbone.sync = function(method, model, options) {
  971. var type = methodMap[method];
  972. // Default options, unless specified.
  973. _.defaults(options || (options = {}), {
  974. emulateHTTP: Backbone.emulateHTTP,
  975. emulateJSON: Backbone.emulateJSON
  976. });
  977. // Default JSON-request options.
  978. var params = {type: type, dataType: 'json'};
  979. // Ensure that we have a URL.
  980. if (!options.url) {
  981. params.url = _.result(model, 'url') || urlError();
  982. }
  983. // Ensure that we have the appropriate request data.
  984. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  985. params.contentType = 'application/json';
  986. params.data = JSON.stringify(options.attrs || model.toJSON(options));
  987. }
  988. // For older servers, emulate JSON by encoding the request into an HTML-form.
  989. if (options.emulateJSON) {
  990. params.contentType = 'application/x-www-form-urlencoded';
  991. params.data = params.data ? {model: params.data} : {};
  992. }
  993. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  994. // And an `X-HTTP-Method-Override` header.
  995. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
  996. params.type = 'POST';
  997. if (options.emulateJSON) params.data._method = type;
  998. var beforeSend = options.beforeSend;
  999. options.beforeSend = function(xhr) {
  1000. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  1001. if (beforeSend) return beforeSend.apply(this, arguments);
  1002. };
  1003. }
  1004. // Don't process data on a non-GET request.
  1005. if (params.type !== 'GET' && !options.emulateJSON) {
  1006. params.processData = false;
  1007. }
  1008. // If we're sending a `PATCH` request, and we're in an old Internet Explorer
  1009. // that still has ActiveX enabled by default, override jQuery to use that
  1010. // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
  1011. if (params.type === 'PATCH' && window.ActiveXObject &&
  1012. !(window.external && window.external.msActiveXFilteringEnabled)) {
  1013. params.xhr = function() {
  1014. return new ActiveXObject("Microsoft.XMLHTTP");
  1015. };
  1016. }
  1017. // Make the request, allowing the user to override any Ajax options.
  1018. var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
  1019. model.trigger('request', model, xhr, options);
  1020. return xhr;
  1021. };
  1022. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  1023. var methodMap = {
  1024. 'create': 'POST',
  1025. 'update': 'PUT',
  1026. 'patch': 'PATCH',
  1027. 'delete': 'DELETE',
  1028. 'read': 'GET'
  1029. };
  1030. // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  1031. // Override this if you'd like to use a different library.
  1032. Backbone.ajax = function() {
  1033. return Backbone.$.ajax.apply(Backbone.$, arguments);
  1034. };
  1035. // Backbone.Router
  1036. // ---------------
  1037. // Routers map faux-URLs to actions, and fire events when routes are
  1038. // matched. Creating a new one sets its `routes` hash, if not set statically.
  1039. var Router = Backbone.Router = function(options) {
  1040. options || (options = {});
  1041. if (options.routes) this.routes = options.routes;
  1042. this._bindRoutes();
  1043. this.initialize.apply(this, arguments);
  1044. };
  1045. // Cached regular expressions for matching named param parts and splatted
  1046. // parts of route strings.
  1047. var optionalParam = /\((.*?)\)/g;
  1048. var namedParam = /(\(\?)?:\w+/g;
  1049. var splatParam = /\*\w+/g;
  1050. var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
  1051. // Set up all inheritable **Backbone.Router** properties and methods.
  1052. _.extend(Router.prototype, Events, {
  1053. // Initialize is an empty function by default. Override it with your own
  1054. // initialization logic.
  1055. initialize: function(){},
  1056. // Manually bind a single named route to a callback. For example:
  1057. //
  1058. // this.route('search/:query/p:num', 'search', function(query, num) {
  1059. // ...
  1060. // });
  1061. //
  1062. route: function(route, name, callback) {
  1063. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  1064. if (_.isFunction(name)) {
  1065. callback = name;
  1066. name = '';
  1067. }
  1068. if (!callback) callback = this[name];
  1069. var router = this;
  1070. Backbone.history.route(route, function(fragment) {
  1071. var args = router._extractParameters(route, fragment);
  1072. callback && callback.apply(router, args);
  1073. router.trigger.apply(router, ['route:' + name].concat(args));
  1074. router.trigger('route', name, args);
  1075. Backbone.history.trigger('route', router, name, args);
  1076. });
  1077. return this;
  1078. },
  1079. // Simple proxy to `Backbone.history` to save a fragment into the history.
  1080. navigate: function(fragment, options) {
  1081. Backbone.history.navigate(fragment, options);
  1082. return this;
  1083. },
  1084. // Bind all defined routes to `Backbone.history`. We have to reverse the
  1085. // order of the routes here to support behavior where the most general
  1086. // routes can be defined at the bottom of the route map.
  1087. _bindRoutes: function() {
  1088. if (!this.routes) return;
  1089. this.routes = _.result(this, 'routes');
  1090. var route, routes = _.keys(this.routes);
  1091. while ((route = routes.pop()) != null) {
  1092. this.route(route, this.routes[route]);
  1093. }
  1094. },
  1095. // Convert a route string into a regular expression, suitable for matching
  1096. // against the current location hash.
  1097. _routeToRegExp: function(route) {
  1098. route = route.replace(escapeRegExp, '\\$&')
  1099. .replace(optionalParam, '(?:$1)?')
  1100. .replace(namedParam, function(match, optional){
  1101. return optional ? match : '([^\/]+)';
  1102. })
  1103. .replace(splatParam, '(.*?)');
  1104. return new RegExp('^' + route + '$');
  1105. },
  1106. // Given a route, and a URL fragment that it matches, return the array of
  1107. // extracted decoded parameters. Empty or unmatched parameters will be
  1108. // treated as `null` to normalize cross-browser behavior.
  1109. _extractParameters: function(route, fragment) {
  1110. var params = route.exec(fragment).slice(1);
  1111. return _.map(params, function(param) {
  1112. return param ? decodeURIComponent(param) : null;
  1113. });
  1114. }
  1115. });
  1116. // Backbone.History
  1117. // ----------------
  1118. // Handles cross-browser history management, based on either
  1119. // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
  1120. // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
  1121. // and URL fragments. If the browser supports neither (old IE, natch),
  1122. // falls back to polling.
  1123. var History = Backbone.History = function() {
  1124. this.handlers = [];
  1125. _.bindAll(this, 'checkUrl');
  1126. // Ensure that `History` can be used outside of the browser.
  1127. if (typeof window !== 'undefined') {
  1128. this.location = window.location;
  1129. this.history = window.history;
  1130. }
  1131. };
  1132. // Cached regex for stripping a leading hash/slash and trailing space.
  1133. var routeStripper = /^[#\/]|\s+$/g;
  1134. // Cached regex for stripping leading and trailing slashes.
  1135. var rootStripper = /^\/+|\/+$/g;
  1136. // Cached regex for detecting MSIE.
  1137. var isExplorer = /msie [\w.]+/;
  1138. // Cached regex for removing a trailing slash.
  1139. var trailingSlash = /\/$/;
  1140. // Has the history handling already been started?
  1141. History.started = false;
  1142. // Set up all inheritable **Backbone.History** properties and methods.
  1143. _.extend(History.prototype, Events, {
  1144. // The default interval to poll for hash changes, if necessary, is
  1145. // twenty times a second.
  1146. interval: 50,
  1147. // Gets the true hash value. Cannot use location.hash directly due to bug
  1148. // in Firefox where location.hash will always be decoded.
  1149. getHash: function(window) {
  1150. var match = (window || this).location.href.match(/#(.*)$/);
  1151. return match ? match[1] : '';
  1152. },
  1153. // Get the cross-browser normalized URL fragment, either from the URL,
  1154. // the hash, or the overr…

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