backbone.js 70 KB

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