backbone.js 76 KB

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