PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/backbone.js

http://github.com/documentcloud/backbone
JavaScript | 2096 lines | 1260 code | 307 blank | 529 comment | 369 complexity | af9c51ed452521592a39cbe5807b1531 MD5 | raw file

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

  1. // Backbone.js 1.4.0
  2. // (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
  3. // Backbone may be freely distributed under the MIT license.
  4. // For all details and documentation:
  5. // http://backbonejs.org
  6. (function(factory) {
  7. // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  8. // We use `self` instead of `window` for `WebWorker` support.
  9. var root = typeof self == 'object' && self.self === self && self ||
  10. typeof global == 'object' && global.global === global && global;
  11. // Set up Backbone appropriately for the environment. Start with AMD.
  12. if (typeof define === 'function' && define.amd) {
  13. define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
  14. // Export global even in AMD case in case this script is loaded with
  15. // others that may still expect a global Backbone.
  16. root.Backbone = factory(root, exports, _, $);
  17. });
  18. // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  19. } else if (typeof exports !== 'undefined') {
  20. var _ = require('underscore'), $;
  21. try { $ = require('jquery'); } catch (e) {}
  22. factory(root, exports, _, $);
  23. // Finally, as a browser global.
  24. } else {
  25. root.Backbone = factory(root, {}, root._, root.jQuery || root.Zepto || root.ender || root.$);
  26. }
  27. })(function(root, Backbone, _, $) {
  28. // Initial Setup
  29. // -------------
  30. // Save the previous value of the `Backbone` variable, so that it can be
  31. // restored later on, if `noConflict` is used.
  32. var previousBackbone = root.Backbone;
  33. // Create a local reference to a common array method we'll want to use later.
  34. var slice = Array.prototype.slice;
  35. // Current version of the library. Keep in sync with `package.json`.
  36. Backbone.VERSION = '1.4.0';
  37. // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
  38. // the `$` variable.
  39. Backbone.$ = $;
  40. // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  41. // to its previous owner. Returns a reference to this Backbone object.
  42. Backbone.noConflict = function() {
  43. root.Backbone = previousBackbone;
  44. return this;
  45. };
  46. // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  47. // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  48. // set a `X-Http-Method-Override` header.
  49. Backbone.emulateHTTP = false;
  50. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  51. // `application/json` requests ... this will encode the body as
  52. // `application/x-www-form-urlencoded` instead and will send the model in a
  53. // form param named `model`.
  54. Backbone.emulateJSON = false;
  55. // Backbone.Events
  56. // ---------------
  57. // A module that can be mixed in to *any object* in order to provide it with
  58. // a custom event channel. You may bind a callback to an event with `on` or
  59. // remove with `off`; `trigger`-ing an event fires all callbacks in
  60. // succession.
  61. //
  62. // var object = {};
  63. // _.extend(object, Backbone.Events);
  64. // object.on('expand', function(){ alert('expanded'); });
  65. // object.trigger('expand');
  66. //
  67. var Events = Backbone.Events = {};
  68. // Regular expression used to split event strings.
  69. var eventSplitter = /\s+/;
  70. // A private global variable to share between listeners and listenees.
  71. var _listening;
  72. // Iterates over the standard `event, callback` (as well as the fancy multiple
  73. // space-separated events `"change blur", callback` and jQuery-style event
  74. // maps `{event: callback}`).
  75. var eventsApi = function(iteratee, events, name, callback, opts) {
  76. var i = 0, names;
  77. if (name && typeof name === 'object') {
  78. // Handle event maps.
  79. if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
  80. for (names = _.keys(name); i < names.length ; i++) {
  81. events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
  82. }
  83. } else if (name && eventSplitter.test(name)) {
  84. // Handle space-separated event names by delegating them individually.
  85. for (names = name.split(eventSplitter); i < names.length; i++) {
  86. events = iteratee(events, names[i], callback, opts);
  87. }
  88. } else {
  89. // Finally, standard events.
  90. events = iteratee(events, name, callback, opts);
  91. }
  92. return events;
  93. };
  94. // Bind an event to a `callback` function. Passing `"all"` will bind
  95. // the callback to all events fired.
  96. Events.on = function(name, callback, context) {
  97. this._events = eventsApi(onApi, this._events || {}, name, callback, {
  98. context: context,
  99. ctx: this,
  100. listening: _listening
  101. });
  102. if (_listening) {
  103. var listeners = this._listeners || (this._listeners = {});
  104. listeners[_listening.id] = _listening;
  105. // Allow the listening to use a counter, instead of tracking
  106. // callbacks for library interop
  107. _listening.interop = false;
  108. }
  109. return this;
  110. };
  111. // Inversion-of-control versions of `on`. Tell *this* object to listen to
  112. // an event in another object... keeping track of what it's listening to
  113. // for easier unbinding later.
  114. Events.listenTo = function(obj, name, callback) {
  115. if (!obj) return this;
  116. var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
  117. var listeningTo = this._listeningTo || (this._listeningTo = {});
  118. var listening = _listening = listeningTo[id];
  119. // This object is not listening to any other events on `obj` yet.
  120. // Setup the necessary references to track the listening callbacks.
  121. if (!listening) {
  122. this._listenId || (this._listenId = _.uniqueId('l'));
  123. listening = _listening = listeningTo[id] = new Listening(this, obj);
  124. }
  125. // Bind callbacks on obj.
  126. var error = tryCatchOn(obj, name, callback, this);
  127. _listening = void 0;
  128. if (error) throw error;
  129. // If the target obj is not Backbone.Events, track events manually.
  130. if (listening.interop) listening.on(name, callback);
  131. return this;
  132. };
  133. // The reducing API that adds a callback to the `events` object.
  134. var onApi = function(events, name, callback, options) {
  135. if (callback) {
  136. var handlers = events[name] || (events[name] = []);
  137. var context = options.context, ctx = options.ctx, listening = options.listening;
  138. if (listening) listening.count++;
  139. handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
  140. }
  141. return events;
  142. };
  143. // An try-catch guarded #on function, to prevent poisoning the global
  144. // `_listening` variable.
  145. var tryCatchOn = function(obj, name, callback, context) {
  146. try {
  147. obj.on(name, callback, context);
  148. } catch (e) {
  149. return e;
  150. }
  151. };
  152. // Remove one or many callbacks. If `context` is null, removes all
  153. // callbacks with that function. If `callback` is null, removes all
  154. // callbacks for the event. If `name` is null, removes all bound
  155. // callbacks for all events.
  156. Events.off = function(name, callback, context) {
  157. if (!this._events) return this;
  158. this._events = eventsApi(offApi, this._events, name, callback, {
  159. context: context,
  160. listeners: this._listeners
  161. });
  162. return this;
  163. };
  164. // Tell this object to stop listening to either specific events ... or
  165. // to every object it's currently listening to.
  166. Events.stopListening = function(obj, name, callback) {
  167. var listeningTo = this._listeningTo;
  168. if (!listeningTo) return this;
  169. var ids = obj ? [obj._listenId] : _.keys(listeningTo);
  170. for (var i = 0; i < ids.length; i++) {
  171. var listening = listeningTo[ids[i]];
  172. // If listening doesn't exist, this object is not currently
  173. // listening to obj. Break out early.
  174. if (!listening) break;
  175. listening.obj.off(name, callback, this);
  176. if (listening.interop) listening.off(name, callback);
  177. }
  178. if (_.isEmpty(listeningTo)) this._listeningTo = void 0;
  179. return this;
  180. };
  181. // The reducing API that removes a callback from the `events` object.
  182. var offApi = function(events, name, callback, options) {
  183. if (!events) return;
  184. var context = options.context, listeners = options.listeners;
  185. var i = 0, names;
  186. // Delete all event listeners and "drop" events.
  187. if (!name && !context && !callback) {
  188. for (names = _.keys(listeners); i < names.length; i++) {
  189. listeners[names[i]].cleanup();
  190. }
  191. return;
  192. }
  193. names = name ? [name] : _.keys(events);
  194. for (; i < names.length; i++) {
  195. name = names[i];
  196. var handlers = events[name];
  197. // Bail out if there are no events stored.
  198. if (!handlers) break;
  199. // Find any remaining events.
  200. var remaining = [];
  201. for (var j = 0; j < handlers.length; j++) {
  202. var handler = handlers[j];
  203. if (
  204. callback && callback !== handler.callback &&
  205. callback !== handler.callback._callback ||
  206. context && context !== handler.context
  207. ) {
  208. remaining.push(handler);
  209. } else {
  210. var listening = handler.listening;
  211. if (listening) listening.off(name, callback);
  212. }
  213. }
  214. // Replace events if there are any remaining. Otherwise, clean up.
  215. if (remaining.length) {
  216. events[name] = remaining;
  217. } else {
  218. delete events[name];
  219. }
  220. }
  221. return events;
  222. };
  223. // Bind an event to only be triggered a single time. After the first time
  224. // the callback is invoked, its listener will be removed. If multiple events
  225. // are passed in using the space-separated syntax, the handler will fire
  226. // once for each event, not once for a combination of all events.
  227. Events.once = function(name, callback, context) {
  228. // Map the event into a `{event: once}` object.
  229. var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
  230. if (typeof name === 'string' && context == null) callback = void 0;
  231. return this.on(events, callback, context);
  232. };
  233. // Inversion-of-control versions of `once`.
  234. Events.listenToOnce = function(obj, name, callback) {
  235. // Map the event into a `{event: once}` object.
  236. var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
  237. return this.listenTo(obj, events);
  238. };
  239. // Reduces the event callbacks into a map of `{event: onceWrapper}`.
  240. // `offer` unbinds the `onceWrapper` after it has been called.
  241. var onceMap = function(map, name, callback, offer) {
  242. if (callback) {
  243. var once = map[name] = _.once(function() {
  244. offer(name, once);
  245. callback.apply(this, arguments);
  246. });
  247. once._callback = callback;
  248. }
  249. return map;
  250. };
  251. // Trigger one or many events, firing all bound callbacks. Callbacks are
  252. // passed the same arguments as `trigger` is, apart from the event name
  253. // (unless you're listening on `"all"`, which will cause your callback to
  254. // receive the true name of the event as the first argument).
  255. Events.trigger = function(name) {
  256. if (!this._events) return this;
  257. var length = Math.max(0, arguments.length - 1);
  258. var args = Array(length);
  259. for (var i = 0; i < length; i++) args[i] = arguments[i + 1];
  260. eventsApi(triggerApi, this._events, name, void 0, args);
  261. return this;
  262. };
  263. // Handles triggering the appropriate event callbacks.
  264. var triggerApi = function(objEvents, name, callback, args) {
  265. if (objEvents) {
  266. var events = objEvents[name];
  267. var allEvents = objEvents.all;
  268. if (events && allEvents) allEvents = allEvents.slice();
  269. if (events) triggerEvents(events, args);
  270. if (allEvents) triggerEvents(allEvents, [name].concat(args));
  271. }
  272. return objEvents;
  273. };
  274. // A difficult-to-believe, but optimized internal dispatch function for
  275. // triggering events. Tries to keep the usual cases speedy (most internal
  276. // Backbone events have 3 arguments).
  277. var triggerEvents = function(events, args) {
  278. var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
  279. switch (args.length) {
  280. case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
  281. case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
  282. case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
  283. case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
  284. default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
  285. }
  286. };
  287. // A listening class that tracks and cleans up memory bindings
  288. // when all callbacks have been offed.
  289. var Listening = function(listener, obj) {
  290. this.id = listener._listenId;
  291. this.listener = listener;
  292. this.obj = obj;
  293. this.interop = true;
  294. this.count = 0;
  295. this._events = void 0;
  296. };
  297. Listening.prototype.on = Events.on;
  298. // Offs a callback (or several).
  299. // Uses an optimized counter if the listenee uses Backbone.Events.
  300. // Otherwise, falls back to manual tracking to support events
  301. // library interop.
  302. Listening.prototype.off = function(name, callback) {
  303. var cleanup;
  304. if (this.interop) {
  305. this._events = eventsApi(offApi, this._events, name, callback, {
  306. context: void 0,
  307. listeners: void 0
  308. });
  309. cleanup = !this._events;
  310. } else {
  311. this.count--;
  312. cleanup = this.count === 0;
  313. }
  314. if (cleanup) this.cleanup();
  315. };
  316. // Cleans up memory bindings between the listener and the listenee.
  317. Listening.prototype.cleanup = function() {
  318. delete this.listener._listeningTo[this.obj._listenId];
  319. if (!this.interop) delete this.obj._listeners[this.id];
  320. };
  321. // Aliases for backwards compatibility.
  322. Events.bind = Events.on;
  323. Events.unbind = Events.off;
  324. // Allow the `Backbone` object to serve as a global event bus, for folks who
  325. // want global "pubsub" in a convenient place.
  326. _.extend(Backbone, Events);
  327. // Backbone.Model
  328. // --------------
  329. // Backbone **Models** are the basic data object in the framework --
  330. // frequently representing a row in a table in a database on your server.
  331. // A discrete chunk of data and a bunch of useful, related methods for
  332. // performing computations and transformations on that data.
  333. // Create a new model with the specified attributes. A client id (`cid`)
  334. // is automatically generated and assigned for you.
  335. var Model = Backbone.Model = function(attributes, options) {
  336. var attrs = attributes || {};
  337. options || (options = {});
  338. this.preinitialize.apply(this, arguments);
  339. this.cid = _.uniqueId(this.cidPrefix);
  340. this.attributes = {};
  341. if (options.collection) this.collection = options.collection;
  342. if (options.parse) attrs = this.parse(attrs, options) || {};
  343. var defaults = _.result(this, 'defaults');
  344. attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
  345. this.set(attrs, options);
  346. this.changed = {};
  347. this.initialize.apply(this, arguments);
  348. };
  349. // Attach all inheritable methods to the Model prototype.
  350. _.extend(Model.prototype, Events, {
  351. // A hash of attributes whose current and previous value differ.
  352. changed: null,
  353. // The value returned during the last failed validation.
  354. validationError: null,
  355. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  356. // CouchDB users may want to set this to `"_id"`.
  357. idAttribute: 'id',
  358. // The prefix is used to create the client id which is used to identify models locally.
  359. // You may want to override this if you're experiencing name clashes with model ids.
  360. cidPrefix: 'c',
  361. // preinitialize is an empty function by default. You can override it with a function
  362. // or object. preinitialize will run before any instantiation logic is run in the Model.
  363. preinitialize: function(){},
  364. // Initialize is an empty function by default. Override it with your own
  365. // initialization logic.
  366. initialize: function(){},
  367. // Return a copy of the model's `attributes` object.
  368. toJSON: function(options) {
  369. return _.clone(this.attributes);
  370. },
  371. // Proxy `Backbone.sync` by default -- but override this if you need
  372. // custom syncing semantics for *this* particular model.
  373. sync: function() {
  374. return Backbone.sync.apply(this, arguments);
  375. },
  376. // Get the value of an attribute.
  377. get: function(attr) {
  378. return this.attributes[attr];
  379. },
  380. // Get the HTML-escaped value of an attribute.
  381. escape: function(attr) {
  382. return _.escape(this.get(attr));
  383. },
  384. // Returns `true` if the attribute contains a value that is not null
  385. // or undefined.
  386. has: function(attr) {
  387. return this.get(attr) != null;
  388. },
  389. // Special-cased proxy to underscore's `_.matches` method.
  390. matches: function(attrs) {
  391. return !!_.iteratee(attrs, this)(this.attributes);
  392. },
  393. // Set a hash of model attributes on the object, firing `"change"`. This is
  394. // the core primitive operation of a model, updating the data and notifying
  395. // anyone who needs to know about the change in state. The heart of the beast.
  396. set: function(key, val, options) {
  397. if (key == null) return this;
  398. // Handle both `"key", value` and `{key: value}` -style arguments.
  399. var attrs;
  400. if (typeof key === 'object') {
  401. attrs = key;
  402. options = val;
  403. } else {
  404. (attrs = {})[key] = val;
  405. }
  406. options || (options = {});
  407. // Run validation.
  408. if (!this._validate(attrs, options)) return false;
  409. // Extract attributes and options.
  410. var unset = options.unset;
  411. var silent = options.silent;
  412. var changes = [];
  413. var changing = this._changing;
  414. this._changing = true;
  415. if (!changing) {
  416. this._previousAttributes = _.clone(this.attributes);
  417. this.changed = {};
  418. }
  419. var current = this.attributes;
  420. var changed = this.changed;
  421. var prev = this._previousAttributes;
  422. // For each `set` attribute, update or delete the current value.
  423. for (var attr in attrs) {
  424. val = attrs[attr];
  425. if (!_.isEqual(current[attr], val)) changes.push(attr);
  426. if (!_.isEqual(prev[attr], val)) {
  427. changed[attr] = val;
  428. } else {
  429. delete changed[attr];
  430. }
  431. unset ? delete current[attr] : current[attr] = val;
  432. }
  433. // Update the `id`.
  434. if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);
  435. // Trigger all relevant attribute changes.
  436. if (!silent) {
  437. if (changes.length) this._pending = options;
  438. for (var i = 0; i < changes.length; i++) {
  439. this.trigger('change:' + changes[i], this, current[changes[i]], options);
  440. }
  441. }
  442. // You might be wondering why there's a `while` loop here. Changes can
  443. // be recursively nested within `"change"` events.
  444. if (changing) return this;
  445. if (!silent) {
  446. while (this._pending) {
  447. options = this._pending;
  448. this._pending = false;
  449. this.trigger('change', this, options);
  450. }
  451. }
  452. this._pending = false;
  453. this._changing = false;
  454. return this;
  455. },
  456. // Remove an attribute from the model, firing `"change"`. `unset` is a noop
  457. // if the attribute doesn't exist.
  458. unset: function(attr, options) {
  459. return this.set(attr, void 0, _.extend({}, options, {unset: true}));
  460. },
  461. // Clear all attributes on the model, firing `"change"`.
  462. clear: function(options) {
  463. var attrs = {};
  464. for (var key in this.attributes) attrs[key] = void 0;
  465. return this.set(attrs, _.extend({}, options, {unset: true}));
  466. },
  467. // Determine if the model has changed since the last `"change"` event.
  468. // If you specify an attribute name, determine if that attribute has changed.
  469. hasChanged: function(attr) {
  470. if (attr == null) return !_.isEmpty(this.changed);
  471. return _.has(this.changed, attr);
  472. },
  473. // Return an object containing all the attributes that have changed, or
  474. // false if there are no changed attributes. Useful for determining what
  475. // parts of a view need to be updated and/or what attributes need to be
  476. // persisted to the server. Unset attributes will be set to undefined.
  477. // You can also pass an attributes object to diff against the model,
  478. // determining if there *would be* a change.
  479. changedAttributes: function(diff) {
  480. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  481. var old = this._changing ? this._previousAttributes : this.attributes;
  482. var changed = {};
  483. var hasChanged;
  484. for (var attr in diff) {
  485. var val = diff[attr];
  486. if (_.isEqual(old[attr], val)) continue;
  487. changed[attr] = val;
  488. hasChanged = true;
  489. }
  490. return hasChanged ? changed : false;
  491. },
  492. // Get the previous value of an attribute, recorded at the time the last
  493. // `"change"` event was fired.
  494. previous: function(attr) {
  495. if (attr == null || !this._previousAttributes) return null;
  496. return this._previousAttributes[attr];
  497. },
  498. // Get all of the attributes of the model at the time of the previous
  499. // `"change"` event.
  500. previousAttributes: function() {
  501. return _.clone(this._previousAttributes);
  502. },
  503. // Fetch the model from the server, merging the response with the model's
  504. // local attributes. Any changed attributes will trigger a "change" event.
  505. fetch: function(options) {
  506. options = _.extend({parse: true}, options);
  507. var model = this;
  508. var success = options.success;
  509. options.success = function(resp) {
  510. var serverAttrs = options.parse ? model.parse(resp, options) : resp;
  511. if (!model.set(serverAttrs, options)) return false;
  512. if (success) success.call(options.context, model, resp, options);
  513. model.trigger('sync', model, resp, options);
  514. };
  515. wrapError(this, options);
  516. return this.sync('read', this, options);
  517. },
  518. // Set a hash of model attributes, and sync the model to the server.
  519. // If the server returns an attributes hash that differs, the model's
  520. // state will be `set` again.
  521. save: function(key, val, options) {
  522. // Handle both `"key", value` and `{key: value}` -style arguments.
  523. var attrs;
  524. if (key == null || typeof key === 'object') {
  525. attrs = key;
  526. options = val;
  527. } else {
  528. (attrs = {})[key] = val;
  529. }
  530. options = _.extend({validate: true, parse: true}, options);
  531. var wait = options.wait;
  532. // If we're not waiting and attributes exist, save acts as
  533. // `set(attr).save(null, opts)` with validation. Otherwise, check if
  534. // the model will be valid when the attributes, if any, are set.
  535. if (attrs && !wait) {
  536. if (!this.set(attrs, options)) return false;
  537. } else if (!this._validate(attrs, options)) {
  538. return false;
  539. }
  540. // After a successful server-side save, the client is (optionally)
  541. // updated with the server-side state.
  542. var model = this;
  543. var success = options.success;
  544. var attributes = this.attributes;
  545. options.success = function(resp) {
  546. // Ensure attributes are restored during synchronous saves.
  547. model.attributes = attributes;
  548. var serverAttrs = options.parse ? model.parse(resp, options) : resp;
  549. if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
  550. if (serverAttrs && !model.set(serverAttrs, options)) return false;
  551. if (success) success.call(options.context, model, resp, options);
  552. model.trigger('sync', model, resp, options);
  553. };
  554. wrapError(this, options);
  555. // Set temporary attributes if `{wait: true}` to properly find new ids.
  556. if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
  557. var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
  558. if (method === 'patch' && !options.attrs) options.attrs = attrs;
  559. var xhr = this.sync(method, this, options);
  560. // Restore attributes.
  561. this.attributes = attributes;
  562. return xhr;
  563. },
  564. // Destroy this model on the server if it was already persisted.
  565. // Optimistically removes the model from its collection, if it has one.
  566. // If `wait: true` is passed, waits for the server to respond before removal.
  567. destroy: function(options) {
  568. options = options ? _.clone(options) : {};
  569. var model = this;
  570. var success = options.success;
  571. var wait = options.wait;
  572. var destroy = function() {
  573. model.stopListening();
  574. model.trigger('destroy', model, model.collection, options);
  575. };
  576. options.success = function(resp) {
  577. if (wait) destroy();
  578. if (success) success.call(options.context, model, resp, options);
  579. if (!model.isNew()) model.trigger('sync', model, resp, options);
  580. };
  581. var xhr = false;
  582. if (this.isNew()) {
  583. _.defer(options.success);
  584. } else {
  585. wrapError(this, options);
  586. xhr = this.sync('delete', this, options);
  587. }
  588. if (!wait) destroy();
  589. return xhr;
  590. },
  591. // Default URL for the model's representation on the server -- if you're
  592. // using Backbone's restful methods, override this to change the endpoint
  593. // that will be called.
  594. url: function() {
  595. var base =
  596. _.result(this, 'urlRoot') ||
  597. _.result(this.collection, 'url') ||
  598. urlError();
  599. if (this.isNew()) return base;
  600. var id = this.get(this.idAttribute);
  601. return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
  602. },
  603. // **parse** converts a response into the hash of attributes to be `set` on
  604. // the model. The default implementation is just to pass the response along.
  605. parse: function(resp, options) {
  606. return resp;
  607. },
  608. // Create a new model with identical attributes to this one.
  609. clone: function() {
  610. return new this.constructor(this.attributes);
  611. },
  612. // A model is new if it has never been saved to the server, and lacks an id.
  613. isNew: function() {
  614. return !this.has(this.idAttribute);
  615. },
  616. // Check if the model is currently in a valid state.
  617. isValid: function(options) {
  618. return this._validate({}, _.extend({}, options, {validate: true}));
  619. },
  620. // Run validation against the next complete set of model attributes,
  621. // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
  622. _validate: function(attrs, options) {
  623. if (!options.validate || !this.validate) return true;
  624. attrs = _.extend({}, this.attributes, attrs);
  625. var error = this.validationError = this.validate(attrs, options) || null;
  626. if (!error) return true;
  627. this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
  628. return false;
  629. }
  630. });
  631. // Backbone.Collection
  632. // -------------------
  633. // If models tend to represent a single row of data, a Backbone Collection is
  634. // more analogous to a table full of data ... or a small slice or page of that
  635. // table, or a collection of rows that belong together for a particular reason
  636. // -- all of the messages in this particular folder, all of the documents
  637. // belonging to this particular author, and so on. Collections maintain
  638. // indexes of their models, both in order, and for lookup by `id`.
  639. // Create a new **Collection**, perhaps to contain a specific type of `model`.
  640. // If a `comparator` is specified, the Collection will maintain
  641. // its models in sort order, as they're added and removed.
  642. var Collection = Backbone.Collection = function(models, options) {
  643. options || (options = {});
  644. this.preinitialize.apply(this, arguments);
  645. if (options.model) this.model = options.model;
  646. if (options.comparator !== void 0) this.comparator = options.comparator;
  647. this._reset();
  648. this.initialize.apply(this, arguments);
  649. if (models) this.reset(models, _.extend({silent: true}, options));
  650. };
  651. // Default options for `Collection#set`.
  652. var setOptions = {add: true, remove: true, merge: true};
  653. var addOptions = {add: true, remove: false};
  654. // Splices `insert` into `array` at index `at`.
  655. var splice = function(array, insert, at) {
  656. at = Math.min(Math.max(at, 0), array.length);
  657. var tail = Array(array.length - at);
  658. var length = insert.length;
  659. var i;
  660. for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
  661. for (i = 0; i < length; i++) array[i + at] = insert[i];
  662. for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
  663. };
  664. // Define the Collection's inheritable methods.
  665. _.extend(Collection.prototype, Events, {
  666. // The default model for a collection is just a **Backbone.Model**.
  667. // This should be overridden in most cases.
  668. model: Model,
  669. // preinitialize is an empty function by default. You can override it with a function
  670. // or object. preinitialize will run before any instantiation logic is run in the Collection.
  671. preinitialize: function(){},
  672. // Initialize is an empty function by default. Override it with your own
  673. // initialization logic.
  674. initialize: function(){},
  675. // The JSON representation of a Collection is an array of the
  676. // models' attributes.
  677. toJSON: function(options) {
  678. return this.map(function(model) { return model.toJSON(options); });
  679. },
  680. // Proxy `Backbone.sync` by default.
  681. sync: function() {
  682. return Backbone.sync.apply(this, arguments);
  683. },
  684. // Add a model, or list of models to the set. `models` may be Backbone
  685. // Models or raw JavaScript objects to be converted to Models, or any
  686. // combination of the two.
  687. add: function(models, options) {
  688. return this.set(models, _.extend({merge: false}, options, addOptions));
  689. },
  690. // Remove a model, or a list of models from the set.
  691. remove: function(models, options) {
  692. options = _.extend({}, options);
  693. var singular = !_.isArray(models);
  694. models = singular ? [models] : models.slice();
  695. var removed = this._removeModels(models, options);
  696. if (!options.silent && removed.length) {
  697. options.changes = {added: [], merged: [], removed: removed};
  698. this.trigger('update', this, options);
  699. }
  700. return singular ? removed[0] : removed;
  701. },
  702. // Update a collection by `set`-ing a new list of models, adding new ones,
  703. // removing models that are no longer present, and merging models that
  704. // already exist in the collection, as necessary. Similar to **Model#set**,
  705. // the core operation for updating the data contained by the collection.
  706. set: function(models, options) {
  707. if (models == null) return;
  708. options = _.extend({}, setOptions, options);
  709. if (options.parse && !this._isModel(models)) {
  710. models = this.parse(models, options) || [];
  711. }
  712. var singular = !_.isArray(models);
  713. models = singular ? [models] : models.slice();
  714. var at = options.at;
  715. if (at != null) at = +at;
  716. if (at > this.length) at = this.length;
  717. if (at < 0) at += this.length + 1;
  718. var set = [];
  719. var toAdd = [];
  720. var toMerge = [];
  721. var toRemove = [];
  722. var modelMap = {};
  723. var add = options.add;
  724. var merge = options.merge;
  725. var remove = options.remove;
  726. var sort = false;
  727. var sortable = this.comparator && at == null && options.sort !== false;
  728. var sortAttr = _.isString(this.comparator) ? this.comparator : null;
  729. // Turn bare objects into model references, and prevent invalid models
  730. // from being added.
  731. var model, i;
  732. for (i = 0; i < models.length; i++) {
  733. model = models[i];
  734. // If a duplicate is found, prevent it from being added and
  735. // optionally merge it into the existing model.
  736. var existing = this.get(model);
  737. if (existing) {
  738. if (merge && model !== existing) {
  739. var attrs = this._isModel(model) ? model.attributes : model;
  740. if (options.parse) attrs = existing.parse(attrs, options);
  741. existing.set(attrs, options);
  742. toMerge.push(existing);
  743. if (sortable && !sort) sort = existing.hasChanged(sortAttr);
  744. }
  745. if (!modelMap[existing.cid]) {
  746. modelMap[existing.cid] = true;
  747. set.push(existing);
  748. }
  749. models[i] = existing;
  750. // If this is a new, valid model, push it to the `toAdd` list.
  751. } else if (add) {
  752. model = models[i] = this._prepareModel(model, options);
  753. if (model) {
  754. toAdd.push(model);
  755. this._addReference(model, options);
  756. modelMap[model.cid] = true;
  757. set.push(model);
  758. }
  759. }
  760. }
  761. // Remove stale models.
  762. if (remove) {
  763. for (i = 0; i < this.length; i++) {
  764. model = this.models[i];
  765. if (!modelMap[model.cid]) toRemove.push(model);
  766. }
  767. if (toRemove.length) this._removeModels(toRemove, options);
  768. }
  769. // See if sorting is needed, update `length` and splice in new models.
  770. var orderChanged = false;
  771. var replace = !sortable && add && remove;
  772. if (set.length && replace) {
  773. orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
  774. return m !== set[index];
  775. });
  776. this.models.length = 0;
  777. splice(this.models, set, 0);
  778. this.length = this.models.length;
  779. } else if (toAdd.length) {
  780. if (sortable) sort = true;
  781. splice(this.models, toAdd, at == null ? this.length : at);
  782. this.length = this.models.length;
  783. }
  784. // Silently sort the collection if appropriate.
  785. if (sort) this.sort({silent: true});
  786. // Unless silenced, it's time to fire all appropriate add/sort/update events.
  787. if (!options.silent) {
  788. for (i = 0; i < toAdd.length; i++) {
  789. if (at != null) options.index = at + i;
  790. model = toAdd[i];
  791. model.trigger('add', model, this, options);
  792. }
  793. if (sort || orderChanged) this.trigger('sort', this, options);
  794. if (toAdd.length || toRemove.length || toMerge.length) {
  795. options.changes = {
  796. added: toAdd,
  797. removed: toRemove,
  798. merged: toMerge
  799. };
  800. this.trigger('update', this, options);
  801. }
  802. }
  803. // Return the added (or merged) model (or models).
  804. return singular ? models[0] : models;
  805. },
  806. // When you have more items than you want to add or remove individually,
  807. // you can reset the entire set with a new list of models, without firing
  808. // any granular `add` or `remove` events. Fires `reset` when finished.
  809. // Useful for bulk operations and optimizations.
  810. reset: function(models, options) {
  811. options = options ? _.clone(options) : {};
  812. for (var i = 0; i < this.models.length; i++) {
  813. this._removeReference(this.models[i], options);
  814. }
  815. options.previousModels = this.models;
  816. this._reset();
  817. models = this.add(models, _.extend({silent: true}, options));
  818. if (!options.silent) this.trigger('reset', this, options);
  819. return models;
  820. },
  821. // Add a model to the end of the collection.
  822. push: function(model, options) {
  823. return this.add(model, _.extend({at: this.length}, options));
  824. },
  825. // Remove a model from the end of the collection.
  826. pop: function(options) {
  827. var model = this.at(this.length - 1);
  828. return this.remove(model, options);
  829. },
  830. // Add a model to the beginning of the collection.
  831. unshift: function(model, options) {
  832. return this.add(model, _.extend({at: 0}, options));
  833. },
  834. // Remove a model from the beginning of the collection.
  835. shift: function(options) {
  836. var model = this.at(0);
  837. return this.remove(model, options);
  838. },
  839. // Slice out a sub-array of models from the collection.
  840. slice: function() {
  841. return slice.apply(this.models, arguments);
  842. },
  843. // Get a model from the set by id, cid, model object with id or cid
  844. // properties, or an attributes object that is transformed through modelId.
  845. get: function(obj) {
  846. if (obj == null) return void 0;
  847. return this._byId[obj] ||
  848. this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj, obj.idAttribute)] ||
  849. obj.cid && this._byId[obj.cid];
  850. },
  851. // Returns `true` if the model is in the collection.
  852. has: function(obj) {
  853. return this.get(obj) != null;
  854. },
  855. // Get the model at the given index.
  856. at: function(index) {
  857. if (index < 0) index += this.length;
  858. return this.models[index];
  859. },
  860. // Return models with matching attributes. Useful for simple cases of
  861. // `filter`.
  862. where: function(attrs, first) {
  863. return this[first ? 'find' : 'filter'](attrs);
  864. },
  865. // Return the first model with matching attributes. Useful for simple cases
  866. // of `find`.
  867. findWhere: function(attrs) {
  868. return this.where(attrs, true);
  869. },
  870. // Force the collection to re-sort itself. You don't need to call this under
  871. // normal circumstances, as the set will maintain sort order as each item
  872. // is added.
  873. sort: function(options) {
  874. var comparator = this.comparator;
  875. if (!comparator) throw new Error('Cannot sort a set without a comparator');
  876. options || (options = {});
  877. var length = comparator.length;
  878. if (_.isFunction(comparator)) comparator = comparator.bind(this);
  879. // Run sort based on type of `comparator`.
  880. if (length === 1 || _.isString(comparator)) {
  881. this.models = this.sortBy(comparator);
  882. } else {
  883. this.models.sort(comparator);
  884. }
  885. if (!options.silent) this.trigger('sort', this, options);
  886. return this;
  887. },
  888. // Pluck an attribute from each model in the collection.
  889. pluck: function(attr) {
  890. return this.map(attr + '');
  891. },
  892. // Fetch the default set of models for this collection, resetting the
  893. // collection when they arrive. If `reset: true` is passed, the response
  894. // data will be passed through the `reset` method instead of `set`.
  895. fetch: function(options) {
  896. options = _.extend({parse: true}, options);
  897. var success = options.success;
  898. var collection = this;
  899. options.success = function(resp) {
  900. var method = options.reset ? 'reset' : 'set';
  901. collection[method](resp, options);
  902. if (success) success.call(options.context, collection, resp, options);
  903. collection.trigger('sync', collection, resp, options);
  904. };
  905. wrapError(this, options);
  906. return this.sync('read', this, options);
  907. },
  908. // Create a new instance of a model in this collection. Add the model to the
  909. // collection immediately, unless `wait: true` is passed, in which case we
  910. // wait for the server to agree.
  911. create: function(model, options) {
  912. options = options ? _.clone(options) : {};
  913. var wait = options.wait;
  914. model = this._prepareModel(model, options);
  915. if (!model) return false;
  916. if (!wait) this.add(model, options);
  917. var collection = this;
  918. var success = options.success;
  919. options.success = function(m, resp, callbackOpts) {
  920. if (wait) collection.add(m, callbackOpts);
  921. if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
  922. };
  923. model.save(null, options);
  924. return model;
  925. },
  926. // **parse** converts a response into a list of models to be added to the
  927. // collection. The default implementation is just to pass it through.
  928. parse: function(resp, options) {
  929. return resp;
  930. },
  931. // Create a new collection with an identical list of models as this one.
  932. clone: function() {
  933. return new this.constructor(this.models, {
  934. model: this.model,
  935. comparator: this.comparator
  936. });
  937. },
  938. // Define how to uniquely identify models in the collection.
  939. modelId: function(attrs, idAttribute) {
  940. return attrs[idAttribute || this.model.prototype.idAttribute || 'id'];
  941. },
  942. // Get an iterator of all models in this collection.
  943. values: function() {
  944. return new CollectionIterator(this, ITERATOR_VALUES);
  945. },
  946. // Get an iterator of all model IDs in this collection.
  947. keys: function() {
  948. return new CollectionIterator(this, ITERATOR_KEYS);
  949. },
  950. // Get an iterator of all [ID, model] tuples in this collection.
  951. entries: function() {
  952. return new CollectionIterator(this, ITERATOR_KEYSVALUES);
  953. },
  954. // Private method to reset all internal state. Called when the collection
  955. // is first initialized or reset.
  956. _reset: function() {
  957. this.length = 0;
  958. this.models = [];
  959. this._byId = {};
  960. },
  961. // Prepare a hash of attributes (or other model) to be added to this
  962. // collection.
  963. _prepareModel: function(attrs, options) {
  964. if (this._isModel(attrs)) {
  965. if (!attrs.collection) attrs.collection = this;
  966. return attrs;
  967. }
  968. options = options ? _.clone(options) : {};
  969. options.collection = this;
  970. var model = new this.model(attrs, options);
  971. if (!model.validationError) return model;
  972. this.trigger('invalid', this, model.validationError, options);
  973. return false;
  974. },
  975. // Internal method called by both remove and set.
  976. _removeModels: function(models, options) {
  977. var removed = [];
  978. for (var i = 0; i < models.length; i++) {
  979. var model = this.get(models[i]);
  980. if (!model) continue;
  981. var index = this.indexOf(model);
  982. this.models.splice(index, 1);
  983. this.length--;
  984. // Remove references before triggering 'remove' event to prevent an
  985. // infinite loop. #3693
  986. delete this._byId[model.cid];
  987. var id = this.modelId(model.attributes, model.idAttribute);
  988. if (id != null) delete this._byId[id];
  989. if (!options.silent) {
  990. options.index = index;
  991. model.trigger('remove', model, this, options);
  992. }
  993. removed.push(model);
  994. this._removeReference(model, options);
  995. }
  996. return removed;
  997. },
  998. // Method for checking whether an object should be considered a model for
  999. // the purposes of adding to the collection.
  1000. _isModel: function(model) {
  1001. return model instanceof Model;
  1002. },
  1003. // Internal method to create a model's ties to a collection.
  1004. _addReference: function(model, options) {
  1005. this._byId[model.cid] = model;
  1006. var id = this.modelId(model.attributes, model.idAttribute);
  1007. if (id != null) this._byId[id] = model;
  1008. model.on('all', this._onModelEvent, this);
  1009. },
  1010. // Internal method to sever a model's ties to a collection.
  1011. _removeReference: function(model, options) {
  1012. delete this._byId[model.cid];
  1013. var id = this.modelId(model.attributes, model.idAttribute);
  1014. if (id != null) delete this._byId[id];
  1015. if (this === model.collection) delete model.collection;
  1016. model.off('all', this._onModelEvent, this);
  1017. },
  1018. // Internal method called every time a model in the set fires an event.
  1019. // Sets need to update their indexes when models change ids. All other
  1020. // events simply proxy through. "add" and "remove" events that originate
  1021. // in other collections are ignored.
  1022. _onModelEvent: function(event, model, collection, options) {
  1023. if (model) {
  1024. if ((event === 'add' || event === 'remove') && collection !== this) return;
  1025. if (event === 'destroy') this.remove(model, options);
  1026. if (event === 'change') {
  1027. var prevId = this.modelId(model.previousAttributes(), model.idAttribute);
  1028. var id = this.modelId(model.attributes, model.idAttribute);
  1029. if (prevId !== id) {
  1030. if (prevId != null) delete this._byId[prevId];
  1031. if (id != null) this._byId[id] = model;
  1032. }
  1033. }
  1034. }
  1035. this.trigger.apply(this, arguments);
  1036. }
  1037. });
  1038. // Defining an @@iterator method implements JavaScript's Iterable protocol.
  1039. // In modern ES2015 browsers, this value is found at Symbol.iterator.
  1040. /* global Symbol */
  1041. var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
  1042. if ($$iterator) {
  1043. Collection.prototype[$$iterator] = Collection.prototype.values;
  1044. }
  1045. // CollectionIterator
  1046. // ------------------
  1047. // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
  1048. // use of `for of` loops in modern browsers and interoperation between
  1049. // Backbone.Collection and other JavaScript functions and third-party libraries
  1050. // which can operate on Iterables.
  1051. var CollectionIterator = function(collection, kind) {
  1052. this._collection = collection;
  1053. this._kind = kind;
  1054. this._index = 0;
  1055. };
  1056. // This "enum" defines the three possible kinds of values which can be emitted
  1057. // by a CollectionIterator that correspond to the values(), keys() and entries()
  1058. // methods on Collection, respectively.
  1059. var ITERATOR_VALUES = 1;
  1060. var ITERATOR_KEYS = 2;
  1061. var ITERATOR_KEYSVALUES = 3;
  1062. // All Iterators should themselves be Iterable.
  1063. if ($$iterator) {
  1064. CollectionIterator.prototype[$$iterator] = function() {
  1065. return this;
  1066. };
  1067. }
  1068. CollectionIterator.prototype.next = function() {
  1069. if (this._collection) {
  1070. // Only continue iterating if the iterated collection is long enough.
  1071. if (this._index < this._collection.length) {
  1072. var model = this._collection.at(this._index);
  1073. this._index++;
  1074. // Construct a value depending on what kind of values should be iterated.
  1075. var value;
  1076. if (this._kind === ITERATOR_VALUES) {
  1077. value = model;
  1078. } else {
  1079. var id = this._collection.modelId(model.attributes);
  1080. if (this._kind === ITERATOR_KEYS) {
  1081. value = id;
  1082. } else { // ITERATOR_KEYSVALUES
  1083. value = [id, model];
  1084. }
  1085. }
  1086. return {value: value, done: false};
  1087. }
  1088. // Once exhausted, remove the reference to the collection so future
  1089. // calls to the next method always return done.
  1090. this._collection = void 0;
  1091. }
  1092. return {value: void 0, done: true};
  1093. };
  1094. // Backbone.View
  1095. // -------------
  1096. // Backbone Views are almost more convention than they are actual code. A View
  1097. // is simply a JavaScript object that represents a logical chunk of UI in the
  1098. // DOM. This might be a single item, an entire list, a sidebar or panel, or
  1099. // even the surrounding frame which wraps your whole app. Defining a chunk of
  1100. // UI as a **View** allows you to define your DOM events declaratively, without
  1101. // having to worry about render order ... and makes it easy for the view to
  1102. // react to specific changes in the state of your models.
  1103. // Creating a Backbone.View creates its initial element outside of the DOM,
  1104. // if an existing element is not provided...
  1105. var View = Backbone.View = function(options) {
  1106. this.cid = _.uniqueId('view');
  1107. this.preinitialize.apply(this, arguments);
  1108. _.extend(this, _.pick(options, viewOptions));
  1109. this._ensureElement();
  1110. this.initialize.apply(this, arguments);
  1111. };
  1112. // Cached regex to split keys for `delegate`.
  1113. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  1114. // List of view options to be set as properties.
  1115. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
  1116. // Set up all inheritable **Backbone.View** properties and methods.
  1117. _.extend(View.prototype, Events, {
  1118. // The default `tagName` of a View's element is `"div"`.
  1119. tagName: 'div',
  1120. // jQuery delegate for element lookup, scoped to DOM elements within the
  1121. // current view. This should be preferred to global lookups where possible.
  1122. $: function(selector) {
  1123. return this.$el.find(selector);
  1124. },
  1125. // preinitialize is an empty function by default. You can override it with a function
  1126. // or object. preinitialize will run before any instantiation logic is run in the View
  1127. preinitialize: function(){},
  1128. // Initialize is an empty function by default. Override it with your own
  1129. // initialization logic.
  1130. initialize: function(){},
  1131. // **render** is the core function that your view should override, in order
  1132. // to populate its element (`this.el`), with the appropriate HTML. The
  1133. // convention is for **render** to always return `this`.
  1134. render: function() {
  1135. return this;
  1136. },
  1137. // Remove this view by taking the element out of the DOM, and removing any
  1138. // applicable Backbone.Events listeners.
  1139. remove: function() {
  1140. this._removeElement();
  1141. this.stopListening();
  1142. return this;
  1143. },
  1144. // Remove this view's element from the document and all event listeners
  1145. // attached to it. Exposed for subclasses using an alternative DOM
  1146. // manipulation API.
  1147. _removeElement: function() {
  1148. this.$el.remove();
  1149. },
  1150. // Change the view's element (`this.el` property) and re-delegate the
  1151. // view's events on the new element.
  1152. setElement: function(element) {
  1153. this.undelegateEvents();
  1154. this._setElement(element);
  1155. this.delegateEvents();
  1156. return this;
  1157. },
  1158. // Creates the `this.el` and `this.$el` references for this view using the
  1159. // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
  1160. // context or an element. Subclasses can override this to utilize an
  1161. // alternative DOM manipulation API and are only required to set the
  1162. // `this.el` property.
  1163. _setElement: function(el) {
  1164. this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
  1165. this.el = this.$el[0];
  1166. },
  1167. // Set callbacks, where `this.events` is a hash of
  1168. //
  1169. // *{"event selector": "callback"}*
  1170. //
  1171. // {
  1172. // 'mousedown .title': 'edit',
  1173. // 'click .button': 'save',
  1174. // 'click .open': function(e) { ... }
  1175. // }
  1176. //
  1177. /

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