backbone.js 71 KB

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