backbone.js 60 KB

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