You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2137 lines
78 KiB

1 year ago
  1. // Backbone.js 1.5.0
  2. // (c) 2010-2022 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.5.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. // Just _.defaults would work fine, but the additional _.extends
  345. // is in there for historical reasons. See #3843.
  346. attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
  347. this.set(attrs, options);
  348. this.changed = {};
  349. this.initialize.apply(this, arguments);
  350. };
  351. // Attach all inheritable methods to the Model prototype.
  352. _.extend(Model.prototype, Events, {
  353. // A hash of attributes whose current and previous value differ.
  354. changed: null,
  355. // The value returned during the last failed validation.
  356. validationError: null,
  357. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  358. // CouchDB users may want to set this to `"_id"`.
  359. idAttribute: 'id',
  360. // The prefix is used to create the client id which is used to identify models locally.
  361. // You may want to override this if you're experiencing name clashes with model ids.
  362. cidPrefix: 'c',
  363. // preinitialize is an empty function by default. You can override it with a function
  364. // or object. preinitialize will run before any instantiation logic is run in the Model.
  365. preinitialize: function(){},
  366. // Initialize is an empty function by default. Override it with your own
  367. // initialization logic.
  368. initialize: function(){},
  369. // Return a copy of the model's `attributes` object.
  370. toJSON: function(options) {
  371. return _.clone(this.attributes);
  372. },
  373. // Proxy `Backbone.sync` by default -- but override this if you need
  374. // custom syncing semantics for *this* particular model.
  375. sync: function() {
  376. return Backbone.sync.apply(this, arguments);
  377. },
  378. // Get the value of an attribute.
  379. get: function(attr) {
  380. return this.attributes[attr];
  381. },
  382. // Get the HTML-escaped value of an attribute.
  383. escape: function(attr) {
  384. return _.escape(this.get(attr));
  385. },
  386. // Returns `true` if the attribute contains a value that is not null
  387. // or undefined.
  388. has: function(attr) {
  389. return this.get(attr) != null;
  390. },
  391. // Special-cased proxy to underscore's `_.matches` method.
  392. matches: function(attrs) {
  393. return !!_.iteratee(attrs, this)(this.attributes);
  394. },
  395. // Set a hash of model attributes on the object, firing `"change"`. This is
  396. // the core primitive operation of a model, updating the data and notifying
  397. // anyone who needs to know about the change in state. The heart of the beast.
  398. set: function(key, val, options) {
  399. if (key == null) return this;
  400. // Handle both `"key", value` and `{key: value}` -style arguments.
  401. var attrs;
  402. if (typeof key === 'object') {
  403. attrs = key;
  404. options = val;
  405. } else {
  406. (attrs = {})[key] = val;
  407. }
  408. options || (options = {});
  409. // Run validation.
  410. if (!this._validate(attrs, options)) return false;
  411. // Extract attributes and options.
  412. var unset = options.unset;
  413. var silent = options.silent;
  414. var changes = [];
  415. var changing = this._changing;
  416. this._changing = true;
  417. if (!changing) {
  418. this._previousAttributes = _.clone(this.attributes);
  419. this.changed = {};
  420. }
  421. var current = this.attributes;
  422. var changed = this.changed;
  423. var prev = this._previousAttributes;
  424. // For each `set` attribute, update or delete the current value.
  425. for (var attr in attrs) {
  426. val = attrs[attr];
  427. if (!_.isEqual(current[attr], val)) changes.push(attr);
  428. if (!_.isEqual(prev[attr], val)) {
  429. changed[attr] = val;
  430. } else {
  431. delete changed[attr];
  432. }
  433. unset ? delete current[attr] : current[attr] = val;
  434. }
  435. // Update the `id`.
  436. if (this.idAttribute in attrs) {
  437. var prevId = this.id;
  438. this.id = this.get(this.idAttribute);
  439. this.trigger('changeId', this, prevId, options);
  440. }
  441. // Trigger all relevant attribute changes.
  442. if (!silent) {
  443. if (changes.length) this._pending = options;
  444. for (var i = 0; i < changes.length; i++) {
  445. this.trigger('change:' + changes[i], this, current[changes[i]], options);
  446. }
  447. }
  448. // You might be wondering why there's a `while` loop here. Changes can
  449. // be recursively nested within `"change"` events.
  450. if (changing) return this;
  451. if (!silent) {
  452. while (this._pending) {
  453. options = this._pending;
  454. this._pending = false;
  455. this.trigger('change', this, options);
  456. }
  457. }
  458. this._pending = false;
  459. this._changing = false;
  460. return this;
  461. },
  462. // Remove an attribute from the model, firing `"change"`. `unset` is a noop
  463. // if the attribute doesn't exist.
  464. unset: function(attr, options) {
  465. return this.set(attr, void 0, _.extend({}, options, {unset: true}));
  466. },
  467. // Clear all attributes on the model, firing `"change"`.
  468. clear: function(options) {
  469. var attrs = {};
  470. for (var key in this.attributes) attrs[key] = void 0;
  471. return this.set(attrs, _.extend({}, options, {unset: true}));
  472. },
  473. // Determine if the model has changed since the last `"change"` event.
  474. // If you specify an attribute name, determine if that attribute has changed.
  475. hasChanged: function(attr) {
  476. if (attr == null) return !_.isEmpty(this.changed);
  477. return _.has(this.changed, attr);
  478. },
  479. // Return an object containing all the attributes that have changed, or
  480. // false if there are no changed attributes. Useful for determining what
  481. // parts of a view need to be updated and/or what attributes need to be
  482. // persisted to the server. Unset attributes will be set to undefined.
  483. // You can also pass an attributes object to diff against the model,
  484. // determining if there *would be* a change.
  485. changedAttributes: function(diff) {
  486. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  487. var old = this._changing ? this._previousAttributes : this.attributes;
  488. var changed = {};
  489. var hasChanged;
  490. for (var attr in diff) {
  491. var val = diff[attr];
  492. if (_.isEqual(old[attr], val)) continue;
  493. changed[attr] = val;
  494. hasChanged = true;
  495. }
  496. return hasChanged ? changed : false;
  497. },
  498. // Get the previous value of an attribute, recorded at the time the last
  499. // `"change"` event was fired.
  500. previous: function(attr) {
  501. if (attr == null || !this._previousAttributes) return null;
  502. return this._previousAttributes[attr];
  503. },
  504. // Get all of the attributes of the model at the time of the previous
  505. // `"change"` event.
  506. previousAttributes: function() {
  507. return _.clone(this._previousAttributes);
  508. },
  509. // Fetch the model from the server, merging the response with the model's
  510. // local attributes. Any changed attributes will trigger a "change" event.
  511. fetch: function(options) {
  512. options = _.extend({parse: true}, options);
  513. var model = this;
  514. var success = options.success;
  515. options.success = function(resp) {
  516. var serverAttrs = options.parse ? model.parse(resp, options) : resp;
  517. if (!model.set(serverAttrs, options)) return false;
  518. if (success) success.call(options.context, model, resp, options);
  519. model.trigger('sync', model, resp, options);
  520. };
  521. wrapError(this, options);
  522. return this.sync('read', this, options);
  523. },
  524. // Set a hash of model attributes, and sync the model to the server.
  525. // If the server returns an attributes hash that differs, the model's
  526. // state will be `set` again.
  527. save: function(key, val, options) {
  528. // Handle both `"key", value` and `{key: value}` -style arguments.
  529. var attrs;
  530. if (key == null || typeof key === 'object') {
  531. attrs = key;
  532. options = val;
  533. } else {
  534. (attrs = {})[key] = val;
  535. }
  536. options = _.extend({validate: true, parse: true}, options);
  537. var wait = options.wait;
  538. // If we're not waiting and attributes exist, save acts as
  539. // `set(attr).save(null, opts)` with validation. Otherwise, check if
  540. // the model will be valid when the attributes, if any, are set.
  541. if (attrs && !wait) {
  542. if (!this.set(attrs, options)) return false;
  543. } else if (!this._validate(attrs, options)) {
  544. return false;
  545. }
  546. // After a successful server-side save, the client is (optionally)
  547. // updated with the server-side state.
  548. var model = this;
  549. var success = options.success;
  550. var attributes = this.attributes;
  551. options.success = function(resp) {
  552. // Ensure attributes are restored during synchronous saves.
  553. model.attributes = attributes;
  554. var serverAttrs = options.parse ? model.parse(resp, options) : resp;
  555. if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
  556. if (serverAttrs && !model.set(serverAttrs, options)) return false;
  557. if (success) success.call(options.context, model, resp, options);
  558. model.trigger('sync', model, resp, options);
  559. };
  560. wrapError(this, options);
  561. // Set temporary attributes if `{wait: true}` to properly find new ids.
  562. if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
  563. var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
  564. if (method === 'patch' && !options.attrs) options.attrs = attrs;
  565. var xhr = this.sync(method, this, options);
  566. // Restore attributes.
  567. this.attributes = attributes;
  568. return xhr;
  569. },
  570. // Destroy this model on the server if it was already persisted.
  571. // Optimistically removes the model from its collection, if it has one.
  572. // If `wait: true` is passed, waits for the server to respond before removal.
  573. destroy: function(options) {
  574. options = options ? _.clone(options) : {};
  575. var model = this;
  576. var success = options.success;
  577. var wait = options.wait;
  578. var destroy = function() {
  579. model.stopListening();
  580. model.trigger('destroy', model, model.collection, options);
  581. };
  582. options.success = function(resp) {
  583. if (wait) destroy();
  584. if (success) success.call(options.context, model, resp, options);
  585. if (!model.isNew()) model.trigger('sync', model, resp, options);
  586. };
  587. var xhr = false;
  588. if (this.isNew()) {
  589. _.defer(options.success);
  590. } else {
  591. wrapError(this, options);
  592. xhr = this.sync('delete', this, options);
  593. }
  594. if (!wait) destroy();
  595. return xhr;
  596. },
  597. // Default URL for the model's representation on the server -- if you're
  598. // using Backbone's restful methods, override this to change the endpoint
  599. // that will be called.
  600. url: function() {
  601. var base =
  602. _.result(this, 'urlRoot') ||
  603. _.result(this.collection, 'url') ||
  604. urlError();
  605. if (this.isNew()) return base;
  606. var id = this.get(this.idAttribute);
  607. return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
  608. },
  609. // **parse** converts a response into the hash of attributes to be `set` on
  610. // the model. The default implementation is just to pass the response along.
  611. parse: function(resp, options) {
  612. return resp;
  613. },
  614. // Create a new model with identical attributes to this one.
  615. clone: function() {
  616. return new this.constructor(this.attributes);
  617. },
  618. // A model is new if it has never been saved to the server, and lacks an id.
  619. isNew: function() {
  620. return !this.has(this.idAttribute);
  621. },
  622. // Check if the model is currently in a valid state.
  623. isValid: function(options) {
  624. return this._validate({}, _.extend({}, options, {validate: true}));
  625. },
  626. // Run validation against the next complete set of model attributes,
  627. // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
  628. _validate: function(attrs, options) {
  629. if (!options.validate || !this.validate) return true;
  630. attrs = _.extend({}, this.attributes, attrs);
  631. var error = this.validationError = this.validate(attrs, options) || null;
  632. if (!error) return true;
  633. this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
  634. return false;
  635. }
  636. });
  637. // Backbone.Collection
  638. // -------------------
  639. // If models tend to represent a single row of data, a Backbone Collection is
  640. // more analogous to a table full of data ... or a small slice or page of that
  641. // table, or a collection of rows that belong together for a particular reason
  642. // -- all of the messages in this particular folder, all of the documents
  643. // belonging to this particular author, and so on. Collections maintain
  644. // indexes of their models, both in order, and for lookup by `id`.
  645. // Create a new **Collection**, perhaps to contain a specific type of `model`.
  646. // If a `comparator` is specified, the Collection will maintain
  647. // its models in sort order, as they're added and removed.
  648. var Collection = Backbone.Collection = function(models, options) {
  649. options || (options = {});
  650. this.preinitialize.apply(this, arguments);
  651. if (options.model) this.model = options.model;
  652. if (options.comparator !== void 0) this.comparator = options.comparator;
  653. this._reset();
  654. this.initialize.apply(this, arguments);
  655. if (models) this.reset(models, _.extend({silent: true}, options));
  656. };
  657. // Default options for `Collection#set`.
  658. var setOptions = {add: true, remove: true, merge: true};
  659. var addOptions = {add: true, remove: false};
  660. // Splices `insert` into `array` at index `at`.
  661. var splice = function(array, insert, at) {
  662. at = Math.min(Math.max(at, 0), array.length);
  663. var tail = Array(array.length - at);
  664. var length = insert.length;
  665. var i;
  666. for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
  667. for (i = 0; i < length; i++) array[i + at] = insert[i];
  668. for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
  669. };
  670. // Define the Collection's inheritable methods.
  671. _.extend(Collection.prototype, Events, {
  672. // The default model for a collection is just a **Backbone.Model**.
  673. // This should be overridden in most cases.
  674. model: Model,
  675. // preinitialize is an empty function by default. You can override it with a function
  676. // or object. preinitialize will run before any instantiation logic is run in the Collection.
  677. preinitialize: function(){},
  678. // Initialize is an empty function by default. Override it with your own
  679. // initialization logic.
  680. initialize: function(){},
  681. // The JSON representation of a Collection is an array of the
  682. // models' attributes.
  683. toJSON: function(options) {
  684. return this.map(function(model) { return model.toJSON(options); });
  685. },
  686. // Proxy `Backbone.sync` by default.
  687. sync: function() {
  688. return Backbone.sync.apply(this, arguments);
  689. },
  690. // Add a model, or list of models to the set. `models` may be Backbone
  691. // Models or raw JavaScript objects to be converted to Models, or any
  692. // combination of the two.
  693. add: function(models, options) {
  694. return this.set(models, _.extend({merge: false}, options, addOptions));
  695. },
  696. // Remove a model, or a list of models from the set.
  697. remove: function(models, options) {
  698. options = _.extend({}, options);
  699. var singular = !_.isArray(models);
  700. models = singular ? [models] : models.slice();
  701. var removed = this._removeModels(models, options);
  702. if (!options.silent && removed.length) {
  703. options.changes = {added: [], merged: [], removed: removed};
  704. this.trigger('update', this, options);
  705. }
  706. return singular ? removed[0] : removed;
  707. },
  708. // Update a collection by `set`-ing a new list of models, adding new ones,
  709. // removing models that are no longer present, and merging models that
  710. // already exist in the collection, as necessary. Similar to **Model#set**,
  711. // the core operation for updating the data contained by the collection.
  712. set: function(models, options) {
  713. if (models == null) return;
  714. options = _.extend({}, setOptions, options);
  715. if (options.parse && !this._isModel(models)) {
  716. models = this.parse(models, options) || [];
  717. }
  718. var singular = !_.isArray(models);
  719. models = singular ? [models] : models.slice();
  720. var at = options.at;
  721. if (at != null) at = +at;
  722. if (at > this.length) at = this.length;
  723. if (at < 0) at += this.length + 1;
  724. var set = [];
  725. var toAdd = [];
  726. var toMerge = [];
  727. var toRemove = [];
  728. var modelMap = {};
  729. var add = options.add;
  730. var merge = options.merge;
  731. var remove = options.remove;
  732. var sort = false;
  733. var sortable = this.comparator && at == null && options.sort !== false;
  734. var sortAttr = _.isString(this.comparator) ? this.comparator : null;
  735. // Turn bare objects into model references, and prevent invalid models
  736. // from being added.
  737. var model, i;
  738. for (i = 0; i < models.length; i++) {
  739. model = models[i];
  740. // If a duplicate is found, prevent it from being added and
  741. // optionally merge it into the existing model.
  742. var existing = this.get(model);
  743. if (existing) {
  744. if (merge && model !== existing) {
  745. var attrs = this._isModel(model) ? model.attributes : model;
  746. if (options.parse) attrs = existing.parse(attrs, options);
  747. existing.set(attrs, options);
  748. toMerge.push(existing);
  749. if (sortable && !sort) sort = existing.hasChanged(sortAttr);
  750. }
  751. if (!modelMap[existing.cid]) {
  752. modelMap[existing.cid] = true;
  753. set.push(existing);
  754. }
  755. models[i] = existing;
  756. // If this is a new, valid model, push it to the `toAdd` list.
  757. } else if (add) {
  758. model = models[i] = this._prepareModel(model, options);
  759. if (model) {
  760. toAdd.push(model);
  761. this._addReference(model, options);
  762. modelMap[model.cid] = true;
  763. set.push(model);
  764. }
  765. }
  766. }
  767. // Remove stale models.
  768. if (remove) {
  769. for (i = 0; i < this.length; i++) {
  770. model = this.models[i];
  771. if (!modelMap[model.cid]) toRemove.push(model);
  772. }
  773. if (toRemove.length) this._removeModels(toRemove, options);
  774. }
  775. // See if sorting is needed, update `length` and splice in new models.
  776. var orderChanged = false;
  777. var replace = !sortable && add && remove;
  778. if (set.length && replace) {
  779. orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
  780. return m !== set[index];
  781. });
  782. this.models.length = 0;
  783. splice(this.models, set, 0);
  784. this.length = this.models.length;
  785. } else if (toAdd.length) {
  786. if (sortable) sort = true;
  787. splice(this.models, toAdd, at == null ? this.length : at);
  788. this.length = this.models.length;
  789. }
  790. // Silently sort the collection if appropriate.
  791. if (sort) this.sort({silent: true});
  792. // Unless silenced, it's time to fire all appropriate add/sort/update events.
  793. if (!options.silent) {
  794. for (i = 0; i < toAdd.length; i++) {
  795. if (at != null) options.index = at + i;
  796. model = toAdd[i];
  797. model.trigger('add', model, this, options);
  798. }
  799. if (sort || orderChanged) this.trigger('sort', this, options);
  800. if (toAdd.length || toRemove.length || toMerge.length) {
  801. options.changes = {
  802. added: toAdd,
  803. removed: toRemove,
  804. merged: toMerge
  805. };
  806. this.trigger('update', this, options);
  807. }
  808. }
  809. // Return the added (or merged) model (or models).
  810. return singular ? models[0] : models;
  811. },
  812. // When you have more items than you want to add or remove individually,
  813. // you can reset the entire set with a new list of models, without firing
  814. // any granular `add` or `remove` events. Fires `reset` when finished.
  815. // Useful for bulk operations and optimizations.
  816. reset: function(models, options) {
  817. options = options ? _.clone(options) : {};
  818. for (var i = 0; i < this.models.length; i++) {
  819. this._removeReference(this.models[i], options);
  820. }
  821. options.previousModels = this.models;
  822. this._reset();
  823. models = this.add(models, _.extend({silent: true}, options));
  824. if (!options.silent) this.trigger('reset', this, options);
  825. return models;
  826. },
  827. // Add a model to the end of the collection.
  828. push: function(model, options) {
  829. return this.add(model, _.extend({at: this.length}, options));
  830. },
  831. // Remove a model from the end of the collection.
  832. pop: function(options) {
  833. var model = this.at(this.length - 1);
  834. return this.remove(model, options);
  835. },
  836. // Add a model to the beginning of the collection.
  837. unshift: function(model, options) {
  838. return this.add(model, _.extend({at: 0}, options));
  839. },
  840. // Remove a model from the beginning of the collection.
  841. shift: function(options) {
  842. var model = this.at(0);
  843. return this.remove(model, options);
  844. },
  845. // Slice out a sub-array of models from the collection.
  846. slice: function() {
  847. return slice.apply(this.models, arguments);
  848. },
  849. // Get a model from the set by id, cid, model object with id or cid
  850. // properties, or an attributes object that is transformed through modelId.
  851. get: function(obj) {
  852. if (obj == null) return void 0;
  853. return this._byId[obj] ||
  854. this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj, obj.idAttribute)] ||
  855. obj.cid && this._byId[obj.cid];
  856. },
  857. // Returns `true` if the model is in the collection.
  858. has: function(obj) {
  859. return this.get(obj) != null;
  860. },
  861. // Get the model at the given index.
  862. at: function(index) {
  863. if (index < 0) index += this.length;
  864. return this.models[index];
  865. },
  866. // Return models with matching attributes. Useful for simple cases of
  867. // `filter`.
  868. where: function(attrs, first) {
  869. return this[first ? 'find' : 'filter'](attrs);
  870. },
  871. // Return the first model with matching attributes. Useful for simple cases
  872. // of `find`.
  873. findWhere: function(attrs) {
  874. return this.where(attrs, true);
  875. },
  876. // Force the collection to re-sort itself. You don't need to call this under
  877. // normal circumstances, as the set will maintain sort order as each item
  878. // is added.
  879. sort: function(options) {
  880. var comparator = this.comparator;
  881. if (!comparator) throw new Error('Cannot sort a set without a comparator');
  882. options || (options = {});
  883. var length = comparator.length;
  884. if (_.isFunction(comparator)) comparator = comparator.bind(this);
  885. // Run sort based on type of `comparator`.
  886. if (length === 1 || _.isString(comparator)) {
  887. this.models = this.sortBy(comparator);
  888. } else {
  889. this.models.sort(comparator);
  890. }
  891. if (!options.silent) this.trigger('sort', this, options);
  892. return this;
  893. },
  894. // Pluck an attribute from each model in the collection.
  895. pluck: function(attr) {
  896. return this.map(attr + '');
  897. },
  898. // Fetch the default set of models for this collection, resetting the
  899. // collection when they arrive. If `reset: true` is passed, the response
  900. // data will be passed through the `reset` method instead of `set`.
  901. fetch: function(options) {
  902. options = _.extend({parse: true}, options);
  903. var success = options.success;
  904. var collection = this;
  905. options.success = function(resp) {
  906. var method = options.reset ? 'reset' : 'set';
  907. collection[method](resp, options);
  908. if (success) success.call(options.context, collection, resp, options);
  909. collection.trigger('sync', collection, resp, options);
  910. };
  911. wrapError(this, options);
  912. return this.sync('read', this, options);
  913. },
  914. // Create a new instance of a model in this collection. Add the model to the
  915. // collection immediately, unless `wait: true` is passed, in which case we
  916. // wait for the server to agree.
  917. create: function(model, options) {
  918. options = options ? _.clone(options) : {};
  919. var wait = options.wait;
  920. model = this._prepareModel(model, options);
  921. if (!model) return false;
  922. if (!wait) this.add(model, options);
  923. var collection = this;
  924. var success = options.success;
  925. options.success = function(m, resp, callbackOpts) {
  926. if (wait) {
  927. m.off('error', this._forwardPristineError, this);
  928. collection.add(m, callbackOpts);
  929. }
  930. if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
  931. };
  932. // In case of wait:true, our collection is not listening to any
  933. // of the model's events yet, so it will not forward the error
  934. // event. In this special case, we need to listen for it
  935. // separately and handle the event just once.
  936. // (The reason we don't need to do this for the sync event is
  937. // in the success handler above: we add the model first, which
  938. // causes the collection to listen, and then invoke the callback
  939. // that triggers the event.)
  940. if (wait) {
  941. model.once('error', this._forwardPristineError, this);
  942. }
  943. model.save(null, options);
  944. return model;
  945. },
  946. // **parse** converts a response into a list of models to be added to the
  947. // collection. The default implementation is just to pass it through.
  948. parse: function(resp, options) {
  949. return resp;
  950. },
  951. // Create a new collection with an identical list of models as this one.
  952. clone: function() {
  953. return new this.constructor(this.models, {
  954. model: this.model,
  955. comparator: this.comparator
  956. });
  957. },
  958. // Define how to uniquely identify models in the collection.
  959. modelId: function(attrs, idAttribute) {
  960. return attrs[idAttribute || this.model.prototype.idAttribute || 'id'];
  961. },
  962. // Get an iterator of all models in this collection.
  963. values: function() {
  964. return new CollectionIterator(this, ITERATOR_VALUES);
  965. },
  966. // Get an iterator of all model IDs in this collection.
  967. keys: function() {
  968. return new CollectionIterator(this, ITERATOR_KEYS);
  969. },
  970. // Get an iterator of all [ID, model] tuples in this collection.
  971. entries: function() {
  972. return new CollectionIterator(this, ITERATOR_KEYSVALUES);
  973. },
  974. // Private method to reset all internal state. Called when the collection
  975. // is first initialized or reset.
  976. _reset: function() {
  977. this.length = 0;
  978. this.models = [];
  979. this._byId = {};
  980. },
  981. // Prepare a hash of attributes (or other model) to be added to this
  982. // collection.
  983. _prepareModel: function(attrs, options) {
  984. if (this._isModel(attrs)) {
  985. if (!attrs.collection) attrs.collection = this;
  986. return attrs;
  987. }
  988. options = options ? _.clone(options) : {};
  989. options.collection = this;
  990. var model;
  991. if (this.model.prototype) {
  992. model = new this.model(attrs, options);
  993. } else {
  994. // ES class methods didn't have prototype
  995. model = this.model(attrs, options);
  996. }
  997. if (!model.validationError) return model;
  998. this.trigger('invalid', this, model.validationError, options);
  999. return false;
  1000. },
  1001. // Internal method called by both remove and set.
  1002. _removeModels: function(models, options) {
  1003. var removed = [];
  1004. for (var i = 0; i < models.length; i++) {
  1005. var model = this.get(models[i]);
  1006. if (!model) continue;
  1007. var index = this.indexOf(model);
  1008. this.models.splice(index, 1);
  1009. this.length--;
  1010. // Remove references before triggering 'remove' event to prevent an
  1011. // infinite loop. #3693
  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 (!options.silent) {
  1016. options.index = index;
  1017. model.trigger('remove', model, this, options);
  1018. }
  1019. removed.push(model);
  1020. this._removeReference(model, options);
  1021. }
  1022. if (models.length > 0 && !options.silent) delete options.index;
  1023. return removed;
  1024. },
  1025. // Method for checking whether an object should be considered a model for
  1026. // the purposes of adding to the collection.
  1027. _isModel: function(model) {
  1028. return model instanceof Model;
  1029. },
  1030. // Internal method to create a model's ties to a collection.
  1031. _addReference: function(model, options) {
  1032. this._byId[model.cid] = model;
  1033. var id = this.modelId(model.attributes, model.idAttribute);
  1034. if (id != null) this._byId[id] = model;
  1035. model.on('all', this._onModelEvent, this);
  1036. },
  1037. // Internal method to sever a model's ties to a collection.
  1038. _removeReference: function(model, options) {
  1039. delete this._byId[model.cid];
  1040. var id = this.modelId(model.attributes, model.idAttribute);
  1041. if (id != null) delete this._byId[id];
  1042. if (this === model.collection) delete model.collection;
  1043. model.off('all', this._onModelEvent, this);
  1044. },
  1045. // Internal method called every time a model in the set fires an event.
  1046. // Sets need to update their indexes when models change ids. All other
  1047. // events simply proxy through. "add" and "remove" events that originate
  1048. // in other collections are ignored.
  1049. _onModelEvent: function(event, model, collection, options) {
  1050. if (model) {
  1051. if ((event === 'add' || event === 'remove') && collection !== this) return;
  1052. if (event === 'destroy') this.remove(model, options);
  1053. if (event === 'changeId') {
  1054. var prevId = this.modelId(model.previousAttributes(), model.idAttribute);
  1055. var id = this.modelId(model.attributes, model.idAttribute);
  1056. if (prevId != null) delete this._byId[prevId];
  1057. if (id != null) this._byId[id] = model;
  1058. }
  1059. }
  1060. this.trigger.apply(this, arguments);
  1061. },
  1062. // Internal callback method used in `create`. It serves as a
  1063. // stand-in for the `_onModelEvent` method, which is not yet bound
  1064. // during the `wait` period of the `create` call. We still want to
  1065. // forward any `'error'` event at the end of the `wait` period,
  1066. // hence a customized callback.
  1067. _forwardPristineError: function(model, collection, options) {
  1068. // Prevent double forward if the model was already in the
  1069. // collection before the call to `create`.
  1070. if (this.has(model)) return;
  1071. this._onModelEvent('error', model, collection, options);
  1072. }
  1073. });
  1074. // Defining an @@iterator method implements JavaScript's Iterable protocol.
  1075. // In modern ES2015 browsers, this value is found at Symbol.iterator.
  1076. /* global Symbol */
  1077. var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
  1078. if ($$iterator) {
  1079. Collection.prototype[$$iterator] = Collection.prototype.values;
  1080. }
  1081. // CollectionIterator
  1082. // ------------------
  1083. // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
  1084. // use of `for of` loops in modern browsers and interoperation between
  1085. // Backbone.Collection and other JavaScript functions and third-party libraries
  1086. // which can operate on Iterables.
  1087. var CollectionIterator = function(collection, kind) {
  1088. this._collection = collection;
  1089. this._kind = kind;
  1090. this._index = 0;
  1091. };
  1092. // This "enum" defines the three possible kinds of values which can be emitted
  1093. // by a CollectionIterator that correspond to the values(), keys() and entries()
  1094. // methods on Collection, respectively.
  1095. var ITERATOR_VALUES = 1;
  1096. var ITERATOR_KEYS = 2;
  1097. var ITERATOR_KEYSVALUES = 3;
  1098. // All Iterators should themselves be Iterable.
  1099. if ($$iterator) {
  1100. CollectionIterator.prototype[$$iterator] = function() {
  1101. return this;
  1102. };
  1103. }
  1104. CollectionIterator.prototype.next = function() {
  1105. if (this._collection) {
  1106. // Only continue iterating if the iterated collection is long enough.
  1107. if (this._index < this._collection.length) {
  1108. var model = this._collection.at(this._index);
  1109. this._index++;
  1110. // Construct a value depending on what kind of values should be iterated.
  1111. var value;
  1112. if (this._kind === ITERATOR_VALUES) {
  1113. value = model;
  1114. } else {
  1115. var id = this._collection.modelId(model.attributes, model.idAttribute);
  1116. if (this._kind === ITERATOR_KEYS) {
  1117. value = id;
  1118. } else { // ITERATOR_KEYSVALUES
  1119. value = [id, model];
  1120. }
  1121. }
  1122. return {value: value, done: false};
  1123. }
  1124. // Once exhausted, remove the reference to the collection so future
  1125. // calls to the next method always return done.
  1126. this._collection = void 0;
  1127. }
  1128. return {value: void 0, done: true};
  1129. };
  1130. // Backbone.View
  1131. // -------------
  1132. // Backbone Views are almost more convention than they are actual code. A View
  1133. // is simply a JavaScript object that represents a logical chunk of UI in the
  1134. // DOM. This might be a single item, an entire list, a sidebar or panel, or
  1135. // even the surrounding frame which wraps your whole app. Defining a chunk of
  1136. // UI as a **View** allows you to define your DOM events declaratively, without
  1137. // having to worry about render order ... and makes it easy for the view to
  1138. // react to specific changes in the state of your models.
  1139. // Creating a Backbone.View creates its initial element outside of the DOM,
  1140. // if an existing element is not provided...
  1141. var View = Backbone.View = function(options) {
  1142. this.cid = _.uniqueId('view');
  1143. this.preinitialize.apply(this, arguments);
  1144. _.extend(this, _.pick(options, viewOptions));
  1145. this._ensureElement();
  1146. this.initialize.apply(this, arguments);
  1147. };
  1148. // Cached regex to split keys for `delegate`.
  1149. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  1150. // List of view options to be set as properties.
  1151. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
  1152. // Set up all inheritable **Backbone.View** properties and methods.
  1153. _.extend(View.prototype, Events, {
  1154. // The default `tagName` of a View's element is `"div"`.
  1155. tagName: 'div',
  1156. // jQuery delegate for element lookup, scoped to DOM elements within the
  1157. // current view. This should be preferred to global lookups where possible.
  1158. $: function(selector) {
  1159. return this.$el.find(selector);
  1160. },
  1161. // preinitialize is an empty function by default. You can override it with a function
  1162. // or object. preinitialize will run before any instantiation logic is run in the View
  1163. preinitialize: function(){},
  1164. // Initialize is an empty function by default. Override it with your own
  1165. // initialization logic.
  1166. initialize: function(){},
  1167. // **render** is the core function that your view should override, in order
  1168. // to populate its element (`this.el`), with the appropriate HTML. The
  1169. // convention is for **render** to always return `this`.
  1170. render: function() {
  1171. return this;
  1172. },
  1173. // Remove this view by taking the element out of the DOM, and removing any
  1174. // applicable Backbone.Events listeners.
  1175. remove: function() {
  1176. this._removeElement();
  1177. this.stopListening();
  1178. return this;
  1179. },
  1180. // Remove this view's element from the document and all event listeners
  1181. // attached to it. Exposed for subclasses using an alternative DOM
  1182. // manipulation API.
  1183. _removeElement: function() {
  1184. this.$el.remove();
  1185. },
  1186. // Change the view's element (`this.el` property) and re-delegate the
  1187. // view's events on the new element.
  1188. setElement: function(element) {
  1189. this.undelegateEvents();
  1190. this._setElement(element);
  1191. this.delegateEvents();
  1192. return this;
  1193. },
  1194. // Creates the `this.el` and `this.$el` references for this view using the
  1195. // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
  1196. // context or an element. Subclasses can override this to utilize an
  1197. // alternative DOM manipulation API and are only required to set the
  1198. // `this.el` property.
  1199. _setElement: function(el) {
  1200. this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
  1201. this.el = this.$el[0];
  1202. },
  1203. // Set callbacks, where `this.events` is a hash of
  1204. //
  1205. // *{"event selector": "callback"}*
  1206. //
  1207. // {
  1208. // 'mousedown .title': 'edit',
  1209. // 'click .button': 'save',
  1210. // 'click .open': function(e) { ... }
  1211. // }
  1212. //
  1213. // pairs. Callbacks will be bound to the view, with `this` set properly.
  1214. // Uses event delegation for efficiency.
  1215. // Omitting the selector binds the event to `this.el`.
  1216. delegateEvents: function(events) {
  1217. events || (events = _.result(this, 'events'));
  1218. if (!events) return this;
  1219. this.undelegateEvents();
  1220. for (var key in events) {
  1221. var method = events[key];
  1222. if (!_.isFunction(method)) method = this[method];
  1223. if (!method) continue;
  1224. var match = key.match(delegateEventSplitter);
  1225. this.delegate(match[1], match[2], method.bind(this));
  1226. }
  1227. return this;
  1228. },
  1229. // Add a single event listener to the view's element (or a child element
  1230. // using `selector`). This only works for delegate-able events: not `focus`,
  1231. // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
  1232. delegate: function(eventName, selector, listener) {
  1233. this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
  1234. return this;
  1235. },
  1236. // Clears all callbacks previously bound to the view by `delegateEvents`.
  1237. // You usually don't need to use this, but may wish to if you have multiple
  1238. // Backbone views attached to the same DOM element.
  1239. undelegateEvents: function() {
  1240. if (this.$el) this.$el.off('.delegateEvents' + this.cid);
  1241. return this;
  1242. },
  1243. // A finer-grained `undelegateEvents` for removing a single delegated event.
  1244. // `selector` and `listener` are both optional.
  1245. undelegate: function(eventName, selector, listener) {
  1246. this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
  1247. return this;
  1248. },
  1249. // Produces a DOM element to be assigned to your view. Exposed for
  1250. // subclasses using an alternative DOM manipulation API.
  1251. _createElement: function(tagName) {
  1252. return document.createElement(tagName);
  1253. },
  1254. // Ensure that the View has a DOM element to render into.
  1255. // If `this.el` is a string, pass it through `$()`, take the first
  1256. // matching element, and re-assign it to `el`. Otherwise, create
  1257. // an element from the `id`, `className` and `tagName` properties.
  1258. _ensureElement: function() {
  1259. if (!this.el) {
  1260. var attrs = _.extend({}, _.result(this, 'attributes'));
  1261. if (this.id) attrs.id = _.result(this, 'id');
  1262. if (this.className) attrs['class'] = _.result(this, 'className');
  1263. this.setElement(this._createElement(_.result(this, 'tagName')));
  1264. this._setAttributes(attrs);
  1265. } else {
  1266. this.setElement(_.result(this, 'el'));
  1267. }
  1268. },
  1269. // Set attributes from a hash on this view's element. Exposed for
  1270. // subclasses using an alternative DOM manipulation API.
  1271. _setAttributes: function(attributes) {
  1272. this.$el.attr(attributes);
  1273. }
  1274. });
  1275. // Proxy Backbone class methods to Underscore functions, wrapping the model's
  1276. // `attributes` object or collection's `models` array behind the scenes.
  1277. //
  1278. // collection.filter(function(model) { return model.get('age') > 10 });
  1279. // collection.each(this.addView);
  1280. //
  1281. // `Function#apply` can be slow so we use the method's arg count, if we know it.
  1282. var addMethod = function(base, length, method, attribute) {
  1283. switch (length) {
  1284. case 1: return function() {
  1285. return base[method](this[attribute]);
  1286. };
  1287. case 2: return function(value) {
  1288. return base[method](this[attribute], value);
  1289. };
  1290. case 3: return function(iteratee, context) {
  1291. return base[method](this[attribute], cb(iteratee, this), context);
  1292. };
  1293. case 4: return function(iteratee, defaultVal, context) {
  1294. return base[method](this[attribute], cb(iteratee, this), defaultVal, context);
  1295. };
  1296. default: return function() {
  1297. var args = slice.call(arguments);
  1298. args.unshift(this[attribute]);
  1299. return base[method].apply(base, args);
  1300. };
  1301. }
  1302. };
  1303. var addUnderscoreMethods = function(Class, base, methods, attribute) {
  1304. _.each(methods, function(length, method) {
  1305. if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute);
  1306. });
  1307. };
  1308. // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
  1309. var cb = function(iteratee, instance) {
  1310. if (_.isFunction(iteratee)) return iteratee;
  1311. if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
  1312. if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
  1313. return iteratee;
  1314. };
  1315. var modelMatcher = function(attrs) {
  1316. var matcher = _.matches(attrs);
  1317. return function(model) {
  1318. return matcher(model.attributes);
  1319. };
  1320. };
  1321. // Underscore methods that we want to implement on the Collection.
  1322. // 90% of the core usefulness of Backbone Collections is actually implemented
  1323. // right here:
  1324. var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
  1325. foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
  1326. select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
  1327. contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
  1328. head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
  1329. without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
  1330. isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
  1331. sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};
  1332. // Underscore methods that we want to implement on the Model, mapped to the
  1333. // number of arguments they take.
  1334. var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
  1335. omit: 0, chain: 1, isEmpty: 1};
  1336. // Mix in each Underscore method as a proxy to `Collection#models`.
  1337. _.each([
  1338. [Collection, collectionMethods, 'models'],
  1339. [Model, modelMethods, 'attributes']
  1340. ], function(config) {
  1341. var Base = config[0],
  1342. methods = config[1],
  1343. attribute = config[2];
  1344. Base.mixin = function(obj) {
  1345. var mappings = _.reduce(_.functions(obj), function(memo, name) {
  1346. memo[name] = 0;
  1347. return memo;
  1348. }, {});
  1349. addUnderscoreMethods(Base, obj, mappings, attribute);
  1350. };
  1351. addUnderscoreMethods(Base, _, methods, attribute);
  1352. });
  1353. // Backbone.sync
  1354. // -------------
  1355. // Override this function to change the manner in which Backbone persists
  1356. // models to the server. You will be passed the type of request, and the
  1357. // model in question. By default, makes a RESTful Ajax request
  1358. // to the model's `url()`. Some possible customizations could be:
  1359. //
  1360. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  1361. // * Send up the models as XML instead of JSON.
  1362. // * Persist models via WebSockets instead of Ajax.
  1363. //
  1364. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  1365. // as `POST`, with a `_method` parameter containing the true HTTP method,
  1366. // as well as all requests with the body as `application/x-www-form-urlencoded`
  1367. // instead of `application/json` with the model in a param named `model`.
  1368. // Useful when interfacing with server-side languages like **PHP** that make
  1369. // it difficult to read the body of `PUT` requests.
  1370. Backbone.sync = function(method, model, options) {
  1371. var type = methodMap[method];
  1372. // Default options, unless specified.
  1373. _.defaults(options || (options = {}), {
  1374. emulateHTTP: Backbone.emulateHTTP,
  1375. emulateJSON: Backbone.emulateJSON
  1376. });
  1377. // Default JSON-request options.
  1378. var params = {type: type, dataType: 'json'};
  1379. // Ensure that we have a URL.
  1380. if (!options.url) {
  1381. params.url = _.result(model, 'url') || urlError();
  1382. }
  1383. // Ensure that we have the appropriate request data.
  1384. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  1385. params.contentType = 'application/json';
  1386. params.data = JSON.stringify(options.attrs || model.toJSON(options));
  1387. }
  1388. // For older servers, emulate JSON by encoding the request into an HTML-form.
  1389. if (options.emulateJSON) {
  1390. params.contentType = 'application/x-www-form-urlencoded';
  1391. params.data = params.data ? {model: params.data} : {};
  1392. }
  1393. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  1394. // And an `X-HTTP-Method-Override` header.
  1395. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
  1396. params.type = 'POST';
  1397. if (options.emulateJSON) params.data._method = type;
  1398. var beforeSend = options.beforeSend;
  1399. options.beforeSend = function(xhr) {
  1400. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  1401. if (beforeSend) return beforeSend.apply(this, arguments);
  1402. };
  1403. }
  1404. // Don't process data on a non-GET request.
  1405. if (params.type !== 'GET' && !options.emulateJSON) {
  1406. params.processData = false;
  1407. }
  1408. // Pass along `textStatus` and `errorThrown` from jQuery.
  1409. var error = options.error;
  1410. options.error = function(xhr, textStatus, errorThrown) {
  1411. options.textStatus = textStatus;
  1412. options.errorThrown = errorThrown;
  1413. if (error) error.call(options.context, xhr, textStatus, errorThrown);
  1414. };
  1415. // Make the request, allowing the user to override any Ajax options.
  1416. var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
  1417. model.trigger('request', model, xhr, options);
  1418. return xhr;
  1419. };
  1420. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  1421. var methodMap = {
  1422. 'create': 'POST',
  1423. 'update': 'PUT',
  1424. 'patch': 'PATCH',
  1425. 'delete': 'DELETE',
  1426. 'read': 'GET'
  1427. };
  1428. // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  1429. // Override this if you'd like to use a different library.
  1430. Backbone.ajax = function() {
  1431. return Backbone.$.ajax.apply(Backbone.$, arguments);
  1432. };
  1433. // Backbone.Router
  1434. // ---------------
  1435. // Routers map faux-URLs to actions, and fire events when routes are
  1436. // matched. Creating a new one sets its `routes` hash, if not set statically.
  1437. var Router = Backbone.Router = function(options) {
  1438. options || (options = {});
  1439. this.preinitialize.apply(this, arguments);
  1440. if (options.routes) this.routes = options.routes;
  1441. this._bindRoutes();
  1442. this.initialize.apply(this, arguments);
  1443. };
  1444. // Cached regular expressions for matching named param parts and splatted
  1445. // parts of route strings.
  1446. var optionalParam = /\((.*?)\)/g;
  1447. var namedParam = /(\(\?)?:\w+/g;
  1448. var splatParam = /\*\w+/g;
  1449. var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
  1450. // Set up all inheritable **Backbone.Router** properties and methods.
  1451. _.extend(Router.prototype, Events, {
  1452. // preinitialize is an empty function by default. You can override it with a function
  1453. // or object. preinitialize will run before any instantiation logic is run in the Router.
  1454. preinitialize: function(){},
  1455. // Initialize is an empty function by default. Override it with your own
  1456. // initialization logic.
  1457. initialize: function(){},
  1458. // Manually bind a single named route to a callback. For example:
  1459. //
  1460. // this.route('search/:query/p:num', 'search', function(query, num) {
  1461. // ...
  1462. // });
  1463. //
  1464. route: function(route, name, callback) {
  1465. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  1466. if (_.isFunction(name)) {
  1467. callback = name;
  1468. name = '';
  1469. }
  1470. if (!callback) callback = this[name];
  1471. var router = this;
  1472. Backbone.history.route(route, function(fragment) {
  1473. var args = router._extractParameters(route, fragment);
  1474. if (router.execute(callback, args, name) !== false) {
  1475. router.trigger.apply(router, ['route:' + name].concat(args));
  1476. router.trigger('route', name, args);
  1477. Backbone.history.trigger('route', router, name, args);
  1478. }
  1479. });
  1480. return this;
  1481. },
  1482. // Execute a route handler with the provided parameters. This is an
  1483. // excellent place to do pre-route setup or post-route cleanup.
  1484. execute: function(callback, args, name) {
  1485. if (callback) callback.apply(this, args);
  1486. },
  1487. // Simple proxy to `Backbone.history` to save a fragment into the history.
  1488. navigate: function(fragment, options) {
  1489. Backbone.history.navigate(fragment, options);
  1490. return this;
  1491. },
  1492. // Bind all defined routes to `Backbone.history`. We have to reverse the
  1493. // order of the routes here to support behavior where the most general
  1494. // routes can be defined at the bottom of the route map.
  1495. _bindRoutes: function() {
  1496. if (!this.routes) return;
  1497. this.routes = _.result(this, 'routes');
  1498. var route, routes = _.keys(this.routes);
  1499. while ((route = routes.pop()) != null) {
  1500. this.route(route, this.routes[route]);
  1501. }
  1502. },
  1503. // Convert a route string into a regular expression, suitable for matching
  1504. // against the current location hash.
  1505. _routeToRegExp: function(route) {
  1506. route = route.replace(escapeRegExp, '\\$&')
  1507. .replace(optionalParam, '(?:$1)?')
  1508. .replace(namedParam, function(match, optional) {
  1509. return optional ? match : '([^/?]+)';
  1510. })
  1511. .replace(splatParam, '([^?]*?)');
  1512. return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
  1513. },
  1514. // Given a route, and a URL fragment that it matches, return the array of
  1515. // extracted decoded parameters. Empty or unmatched parameters will be
  1516. // treated as `null` to normalize cross-browser behavior.
  1517. _extractParameters: function(route, fragment) {
  1518. var params = route.exec(fragment).slice(1);
  1519. return _.map(params, function(param, i) {
  1520. // Don't decode the search params.
  1521. if (i === params.length - 1) return param || null;
  1522. return param ? decodeURIComponent(param) : null;
  1523. });
  1524. }
  1525. });
  1526. // Backbone.History
  1527. // ----------------
  1528. // Handles cross-browser history management, based on either
  1529. // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
  1530. // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
  1531. // and URL fragments. If the browser supports neither (old IE, natch),
  1532. // falls back to polling.
  1533. var History = Backbone.History = function() {
  1534. this.handlers = [];
  1535. this.checkUrl = this.checkUrl.bind(this);
  1536. // Ensure that `History` can be used outside of the browser.
  1537. if (typeof window !== 'undefined') {
  1538. this.location = window.location;
  1539. this.history = window.history;
  1540. }
  1541. };
  1542. // Cached regex for stripping a leading hash/slash and trailing space.
  1543. var routeStripper = /^[#\/]|\s+$/g;
  1544. // Cached regex for stripping leading and trailing slashes.
  1545. var rootStripper = /^\/+|\/+$/g;
  1546. // Cached regex for stripping urls of hash.
  1547. var pathStripper = /#.*$/;
  1548. // Has the history handling already been started?
  1549. History.started = false;
  1550. // Set up all inheritable **Backbone.History** properties and methods.
  1551. _.extend(History.prototype, Events, {
  1552. // The default interval to poll for hash changes, if necessary, is
  1553. // twenty times a second.
  1554. interval: 50,
  1555. // Are we at the app root?
  1556. atRoot: function() {
  1557. var path = this.location.pathname.replace(/[^\/]$/, '$&/');
  1558. return path === this.root && !this.getSearch();
  1559. },
  1560. // Does the pathname match the root?
  1561. matchRoot: function() {
  1562. var path = this.decodeFragment(this.location.pathname);
  1563. var rootPath = path.slice(0, this.root.length - 1) + '/';
  1564. return rootPath === this.root;
  1565. },
  1566. // Unicode characters in `location.pathname` are percent encoded so they're
  1567. // decoded for comparison. `%25` should not be decoded since it may be part
  1568. // of an encoded parameter.
  1569. decodeFragment: function(fragment) {
  1570. return decodeURI(fragment.replace(/%25/g, '%2525'));
  1571. },
  1572. // In IE6, the hash fragment and search params are incorrect if the
  1573. // fragment contains `?`.
  1574. getSearch: function() {
  1575. var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
  1576. return match ? match[0] : '';
  1577. },
  1578. // Gets the true hash value. Cannot use location.hash directly due to bug
  1579. // in Firefox where location.hash will always be decoded.
  1580. getHash: function(window) {
  1581. var match = (window || this).location.href.match(/#(.*)$/);
  1582. return match ? match[1] : '';
  1583. },
  1584. // Get the pathname and search params, without the root.
  1585. getPath: function() {
  1586. var path = this.decodeFragment(
  1587. this.location.pathname + this.getSearch()
  1588. ).slice(this.root.length - 1);
  1589. return path.charAt(0) === '/' ? path.slice(1) : path;
  1590. },
  1591. // Get the cross-browser normalized URL fragment from the path or hash.
  1592. getFragment: function(fragment) {
  1593. if (fragment == null) {
  1594. if (this._usePushState || !this._wantsHashChange) {
  1595. fragment = this.getPath();
  1596. } else {
  1597. fragment = this.getHash();
  1598. }
  1599. }
  1600. return fragment.replace(routeStripper, '');
  1601. },
  1602. // Start the hash change handling, returning `true` if the current URL matches
  1603. // an existing route, and `false` otherwise.
  1604. start: function(options) {
  1605. if (History.started) throw new Error('Backbone.history has already been started');
  1606. History.started = true;
  1607. // Figure out the initial configuration. Do we need an iframe?
  1608. // Is pushState desired ... is it available?
  1609. this.options = _.extend({root: '/'}, this.options, options);
  1610. this.root = this.options.root;
  1611. this._trailingSlash = this.options.trailingSlash;
  1612. this._wantsHashChange = this.options.hashChange !== false;
  1613. this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
  1614. this._useHashChange = this._wantsHashChange && this._hasHashChange;
  1615. this._wantsPushState = !!this.options.pushState;
  1616. this._hasPushState = !!(this.history && this.history.pushState);
  1617. this._usePushState = this._wantsPushState && this._hasPushState;
  1618. this.fragment = this.getFragment();
  1619. // Normalize root to always include a leading and trailing slash.
  1620. this.root = ('/' + this.root + '/').replace(rootStripper, '/');
  1621. // Transition from hashChange to pushState or vice versa if both are
  1622. // requested.
  1623. if (this._wantsHashChange && this._wantsPushState) {
  1624. // If we've started off with a route from a `pushState`-enabled
  1625. // browser, but we're currently in a browser that doesn't support it...
  1626. if (!this._hasPushState && !this.atRoot()) {
  1627. var rootPath = this.root.slice(0, -1) || '/';
  1628. this.location.replace(rootPath + '#' + this.getPath());
  1629. // Return immediately as browser will do redirect to new url
  1630. return true;
  1631. // Or if we've started out with a hash-based route, but we're currently
  1632. // in a browser where it could be `pushState`-based instead...
  1633. } else if (this._hasPushState && this.atRoot()) {
  1634. this.navigate(this.getHash(), {replace: true});
  1635. }
  1636. }
  1637. // Proxy an iframe to handle location events if the browser doesn't
  1638. // support the `hashchange` event, HTML5 history, or the user wants
  1639. // `hashChange` but not `pushState`.
  1640. if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
  1641. this.iframe = document.createElement('iframe');
  1642. this.iframe.src = 'javascript:0';
  1643. this.iframe.style.display = 'none';
  1644. this.iframe.tabIndex = -1;
  1645. var body = document.body;
  1646. // Using `appendChild` will throw on IE < 9 if the document is not ready.
  1647. var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
  1648. iWindow.document.open();
  1649. iWindow.document.close();
  1650. iWindow.location.hash = '#' + this.fragment;
  1651. }
  1652. // Add a cross-platform `addEventListener` shim for older browsers.
  1653. var addEventListener = window.addEventListener || function(eventName, listener) {
  1654. return attachEvent('on' + eventName, listener);
  1655. };
  1656. // Depending on whether we're using pushState or hashes, and whether
  1657. // 'onhashchange' is supported, determine how we check the URL state.
  1658. if (this._usePushState) {
  1659. addEventListener('popstate', this.checkUrl, false);
  1660. } else if (this._useHashChange && !this.iframe) {
  1661. addEventListener('hashchange', this.checkUrl, false);
  1662. } else if (this._wantsHashChange) {
  1663. this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
  1664. }
  1665. if (!this.options.silent) return this.loadUrl();
  1666. },
  1667. // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
  1668. // but possibly useful for unit testing Routers.
  1669. stop: function() {
  1670. // Add a cross-platform `removeEventListener` shim for older browsers.
  1671. var removeEventListener = window.removeEventListener || function(eventName, listener) {
  1672. return detachEvent('on' + eventName, listener);
  1673. };
  1674. // Remove window listeners.
  1675. if (this._usePushState) {
  1676. removeEventListener('popstate', this.checkUrl, false);
  1677. } else if (this._useHashChange && !this.iframe) {
  1678. removeEventListener('hashchange', this.checkUrl, false);
  1679. }
  1680. // Clean up the iframe if necessary.
  1681. if (this.iframe) {
  1682. document.body.removeChild(this.iframe);
  1683. this.iframe = null;
  1684. }
  1685. // Some environments will throw when clearing an undefined interval.
  1686. if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
  1687. History.started = false;
  1688. },
  1689. // Add a route to be tested when the fragment changes. Routes added later
  1690. // may override previous routes.
  1691. route: function(route, callback) {
  1692. this.handlers.unshift({route: route, callback: callback});
  1693. },
  1694. // Checks the current URL to see if it has changed, and if it has,
  1695. // calls `loadUrl`, normalizing across the hidden iframe.
  1696. checkUrl: function(e) {
  1697. var current = this.getFragment();
  1698. // If the user pressed the back button, the iframe's hash will have
  1699. // changed and we should use that for comparison.
  1700. if (current === this.fragment && this.iframe) {
  1701. current = this.getHash(this.iframe.contentWindow);
  1702. }
  1703. if (current === this.fragment) return false;
  1704. if (this.iframe) this.navigate(current);
  1705. this.loadUrl();
  1706. },
  1707. // Attempt to load the current URL fragment. If a route succeeds with a
  1708. // match, returns `true`. If no defined routes matches the fragment,
  1709. // returns `false`.
  1710. loadUrl: function(fragment) {
  1711. // If the root doesn't match, no routes can match either.
  1712. if (!this.matchRoot()) return false;
  1713. fragment = this.fragment = this.getFragment(fragment);
  1714. return _.some(this.handlers, function(handler) {
  1715. if (handler.route.test(fragment)) {
  1716. handler.callback(fragment);
  1717. return true;
  1718. }
  1719. });
  1720. },
  1721. // Save a fragment into the hash history, or replace the URL state if the
  1722. // 'replace' option is passed. You are responsible for properly URL-encoding
  1723. // the fragment in advance.
  1724. //
  1725. // The options object can contain `trigger: true` if you wish to have the
  1726. // route callback be fired (not usually desirable), or `replace: true`, if
  1727. // you wish to modify the current URL without adding an entry to the history.
  1728. navigate: function(fragment, options) {
  1729. if (!History.started) return false;
  1730. if (!options || options === true) options = {trigger: !!options};
  1731. // Normalize the fragment.
  1732. fragment = this.getFragment(fragment || '');
  1733. // Strip trailing slash on the root unless _trailingSlash is true
  1734. var rootPath = this.root;
  1735. if (!this._trailingSlash && (fragment === '' || fragment.charAt(0) === '?')) {
  1736. rootPath = rootPath.slice(0, -1) || '/';
  1737. }
  1738. var url = rootPath + fragment;
  1739. // Strip the fragment of the query and hash for matching.
  1740. fragment = fragment.replace(pathStripper, '');
  1741. // Decode for matching.
  1742. var decodedFragment = this.decodeFragment(fragment);
  1743. if (this.fragment === decodedFragment) return;
  1744. this.fragment = decodedFragment;
  1745. // If pushState is available, we use it to set the fragment as a real URL.
  1746. if (this._usePushState) {
  1747. this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
  1748. // If hash changes haven't been explicitly disabled, update the hash
  1749. // fragment to store history.
  1750. } else if (this._wantsHashChange) {
  1751. this._updateHash(this.location, fragment, options.replace);
  1752. if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
  1753. var iWindow = this.iframe.contentWindow;
  1754. // Opening and closing the iframe tricks IE7 and earlier to push a
  1755. // history entry on hash-tag change. When replace is true, we don't
  1756. // want this.
  1757. if (!options.replace) {
  1758. iWindow.document.open();
  1759. iWindow.document.close();
  1760. }
  1761. this._updateHash(iWindow.location, fragment, options.replace);
  1762. }
  1763. // If you've told us that you explicitly don't want fallback hashchange-
  1764. // based history, then `navigate` becomes a page refresh.
  1765. } else {
  1766. return this.location.assign(url);
  1767. }
  1768. if (options.trigger) return this.loadUrl(fragment);
  1769. },
  1770. // Update the hash location, either replacing the current entry, or adding
  1771. // a new one to the browser history.
  1772. _updateHash: function(location, fragment, replace) {
  1773. if (replace) {
  1774. var href = location.href.replace(/(javascript:|#).*$/, '');
  1775. location.replace(href + '#' + fragment);
  1776. } else {
  1777. // Some browsers require that `hash` contains a leading #.
  1778. location.hash = '#' + fragment;
  1779. }
  1780. }
  1781. });
  1782. // Create the default Backbone.history.
  1783. Backbone.history = new History;
  1784. // Helpers
  1785. // -------
  1786. // Helper function to correctly set up the prototype chain for subclasses.
  1787. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  1788. // class properties to be extended.
  1789. var extend = function(protoProps, staticProps) {
  1790. var parent = this;
  1791. var child;
  1792. // The constructor function for the new subclass is either defined by you
  1793. // (the "constructor" property in your `extend` definition), or defaulted
  1794. // by us to simply call the parent constructor.
  1795. if (protoProps && _.has(protoProps, 'constructor')) {
  1796. child = protoProps.constructor;
  1797. } else {
  1798. child = function(){ return parent.apply(this, arguments); };
  1799. }
  1800. // Add static properties to the constructor function, if supplied.
  1801. _.extend(child, parent, staticProps);
  1802. // Set the prototype chain to inherit from `parent`, without calling
  1803. // `parent`'s constructor function and add the prototype properties.
  1804. child.prototype = _.create(parent.prototype, protoProps);
  1805. child.prototype.constructor = child;
  1806. // Set a convenience property in case the parent's prototype is needed
  1807. // later.
  1808. child.__super__ = parent.prototype;
  1809. return child;
  1810. };
  1811. // Set up inheritance for the model, collection, router, view and history.
  1812. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
  1813. // Throw an error when a URL is needed, and none is supplied.
  1814. var urlError = function() {
  1815. throw new Error('A "url" property or function must be specified');
  1816. };
  1817. // Wrap an optional error callback with a fallback error event.
  1818. var wrapError = function(model, options) {
  1819. var error = options.error;
  1820. options.error = function(resp) {
  1821. if (error) error.call(options.context, model, resp, options);
  1822. model.trigger('error', model, resp, options);
  1823. };
  1824. };
  1825. return Backbone;
  1826. });