backbone.js 65 KB

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