backbone.js 76 KB

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