backbone.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  1. // Backbone.js 0.9.2
  2. // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
  3. // Backbone may be freely distributed under the MIT license.
  4. // For all details and documentation:
  5. // http://backbonejs.org
  6. (function(root, factory) {
  7. // Set up Backbone appropriately for the environment.
  8. /*if (typeof exports !== 'undefined') {
  9. // Node/CommonJS, no need for jQuery in that case.
  10. factory(root, exports, require('libs/underscore'));
  11. } else if (typeof define === 'function' && define.amd) {
  12. // 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. console.log("Backbone jquery", $);
  17. root.Backbone = factory(root, exports, _, $);
  18. });
  19. } else {
  20. // Browser globals*/
  21. root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender));
  22. //}
  23. }(this, function(root, Backbone, _, $) {
  24. // Initial Setup
  25. // -------------
  26. // Save the previous value of the `Backbone` variable, so that it can be
  27. // restored later on, if `noConflict` is used.
  28. var previousBackbone = root.Backbone;
  29. // Create a local reference to slice/splice.
  30. var slice = Array.prototype.slice;
  31. var splice = Array.prototype.splice;
  32. // Current version of the library. Keep in sync with `package.json`.
  33. Backbone.VERSION = '0.9.2';
  34. // Set the JavaScript library that will be used for DOM manipulation and
  35. // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery,
  36. // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an
  37. // alternate JavaScript library (or a mock library for testing your views
  38. // outside of a browser).
  39. Backbone.setDomLibrary = function(lib) {
  40. $ = lib;
  41. };
  42. // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  43. // to its previous owner. Returns a reference to this Backbone object.
  44. Backbone.noConflict = function() {
  45. root.Backbone = previousBackbone;
  46. return Backbone;
  47. };
  48. // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  49. // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  50. // set a `X-Http-Method-Override` header.
  51. Backbone.emulateHTTP = false;
  52. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  53. // `application/json` requests ... will encode the body as
  54. // `application/x-www-form-urlencoded` instead and will send the model in a
  55. // form param named `model`.
  56. Backbone.emulateJSON = false;
  57. // Backbone.Events
  58. // -----------------
  59. // Regular expression used to split event strings
  60. var eventSplitter = /\s+/;
  61. // A module that can be mixed in to *any object* in order to provide it with
  62. // custom events. You may bind with `on` or remove with `off` callback functions
  63. // to an event; trigger`-ing an event fires all callbacks in succession.
  64. //
  65. // var object = {};
  66. // _.extend(object, Backbone.Events);
  67. // object.on('expand', function(){ alert('expanded'); });
  68. // object.trigger('expand');
  69. //
  70. var Events = Backbone.Events = {
  71. // Bind one or more space separated events, `events`, to a `callback`
  72. // function. Passing `"all"` will bind the callback to all events fired.
  73. on: function(events, callback, context) {
  74. var calls, event, node, tail, list;
  75. if (!callback) return this;
  76. events = events.split(eventSplitter);
  77. calls = this._callbacks || (this._callbacks = {});
  78. // Create an immutable callback list, allowing traversal during
  79. // modification. The tail is an empty object that will always be used
  80. // as the next node.
  81. while (event = events.shift()) {
  82. list = calls[event];
  83. node = list ? list.tail : {};
  84. node.next = tail = {};
  85. node.context = context;
  86. node.callback = callback;
  87. calls[event] = {tail: tail, next: list ? list.next : node};
  88. }
  89. return this;
  90. },
  91. // Remove one or many callbacks. If `context` is null, removes all callbacks
  92. // with that function. If `callback` is null, removes all callbacks for the
  93. // event. If `events` is null, removes all bound callbacks for all events.
  94. off: function(events, callback, context) {
  95. var event, calls, node, tail, cb, ctx;
  96. // No events, or removing *all* events.
  97. if (!(calls = this._callbacks)) return;
  98. if (!(events || callback || context)) {
  99. delete this._callbacks;
  100. return this;
  101. }
  102. // Loop through the listed events and contexts, splicing them out of the
  103. // linked list of callbacks if appropriate.
  104. events = events ? events.split(eventSplitter) : _.keys(calls);
  105. while (event = events.shift()) {
  106. node = calls[event];
  107. delete calls[event];
  108. if (!node || !(callback || context)) continue;
  109. // Create a new list, omitting the indicated callbacks.
  110. tail = node.tail;
  111. while ((node = node.next) !== tail) {
  112. cb = node.callback;
  113. ctx = node.context;
  114. if ((callback && cb !== callback) || (context && ctx !== context)) {
  115. this.on(event, cb, ctx);
  116. }
  117. }
  118. }
  119. return this;
  120. },
  121. // Trigger one or many events, firing all bound callbacks. Callbacks are
  122. // passed the same arguments as `trigger` is, apart from the event name
  123. // (unless you're listening on `"all"`, which will cause your callback to
  124. // receive the true name of the event as the first argument).
  125. trigger: function(events) {
  126. var event, node, calls, tail, args, all, rest;
  127. if (!(calls = this._callbacks)) return this;
  128. all = calls.all;
  129. events = events.split(eventSplitter);
  130. rest = slice.call(arguments, 1);
  131. // For each event, walk through the linked list of callbacks twice,
  132. // first to trigger the event, then to trigger any `"all"` callbacks.
  133. while (event = events.shift()) {
  134. if (node = calls[event]) {
  135. tail = node.tail;
  136. while ((node = node.next) !== tail) {
  137. node.callback.apply(node.context || this, rest);
  138. }
  139. }
  140. if (node = all) {
  141. tail = node.tail;
  142. args = [event].concat(rest);
  143. while ((node = node.next) !== tail) {
  144. node.callback.apply(node.context || this, args);
  145. }
  146. }
  147. }
  148. return this;
  149. }
  150. };
  151. // Aliases for backwards compatibility.
  152. Events.bind = Events.on;
  153. Events.unbind = Events.off;
  154. // Backbone.Model
  155. // --------------
  156. // Create a new model, with defined attributes. A client id (`cid`)
  157. // is automatically generated and assigned for you.
  158. var Model = Backbone.Model = function(attributes, options) {
  159. var defaults;
  160. attributes || (attributes = {});
  161. if (options && options.parse) attributes = this.parse(attributes);
  162. if (defaults = getValue(this, 'defaults')) {
  163. attributes = _.extend({}, defaults, attributes);
  164. }
  165. if (options && options.collection) this.collection = options.collection;
  166. this.attributes = {};
  167. this._escapedAttributes = {};
  168. this.cid = _.uniqueId('c');
  169. this.changed = {};
  170. this._silent = {};
  171. this._pending = {};
  172. this.set(attributes, {silent: true});
  173. // Reset change tracking.
  174. this.changed = {};
  175. this._silent = {};
  176. this._pending = {};
  177. this._previousAttributes = _.clone(this.attributes);
  178. this.initialize.apply(this, arguments);
  179. };
  180. // Attach all inheritable methods to the Model prototype.
  181. _.extend(Model.prototype, Events, {
  182. // A hash of attributes whose current and previous value differ.
  183. changed: null,
  184. // A hash of attributes that have silently changed since the last time
  185. // `change` was called. Will become pending attributes on the next call.
  186. _silent: null,
  187. // A hash of attributes that have changed since the last `'change'` event
  188. // began.
  189. _pending: null,
  190. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  191. // CouchDB users may want to set this to `"_id"`.
  192. idAttribute: 'id',
  193. // Initialize is an empty function by default. Override it with your own
  194. // initialization logic.
  195. initialize: function(){},
  196. // Return a copy of the model's `attributes` object.
  197. toJSON: function(options) {
  198. return _.clone(this.attributes);
  199. },
  200. // Get the value of an attribute.
  201. get: function(attr) {
  202. return this.attributes[attr];
  203. },
  204. // Get the HTML-escaped value of an attribute.
  205. escape: function(attr) {
  206. var html;
  207. if (html = this._escapedAttributes[attr]) return html;
  208. var val = this.get(attr);
  209. return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
  210. },
  211. // Returns `true` if the attribute contains a value that is not null
  212. // or undefined.
  213. has: function(attr) {
  214. return this.get(attr) != null;
  215. },
  216. // Set a hash of model attributes on the object, firing `"change"` unless
  217. // you choose to silence it.
  218. set: function(key, value, options) {
  219. var attrs, attr, val;
  220. // Handle both `"key", value` and `{key: value}` -style arguments.
  221. if (_.isObject(key) || key == null) {
  222. attrs = key;
  223. options = value;
  224. } else {
  225. attrs = {};
  226. attrs[key] = value;
  227. }
  228. // Extract attributes and options.
  229. options || (options = {});
  230. if (!attrs) return this;
  231. if (attrs instanceof Model) attrs = attrs.attributes;
  232. if (options.unset) for (attr in attrs) attrs[attr] = void 0;
  233. // Run validation.
  234. if (!this._validate(attrs, options)) return false;
  235. // Check for changes of `id`.
  236. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
  237. var changes = options.changes = {};
  238. var now = this.attributes;
  239. var escaped = this._escapedAttributes;
  240. var prev = this._previousAttributes || {};
  241. // For each `set` attribute...
  242. for (attr in attrs) {
  243. val = attrs[attr];
  244. // If the new and current value differ, record the change.
  245. if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
  246. delete escaped[attr];
  247. (options.silent ? this._silent : changes)[attr] = true;
  248. }
  249. // Update or delete the current value.
  250. options.unset ? delete now[attr] : now[attr] = val;
  251. // If the new and previous value differ, record the change. If not,
  252. // then remove changes for this attribute.
  253. if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
  254. this.changed[attr] = val;
  255. if (!options.silent) this._pending[attr] = true;
  256. } else {
  257. delete this.changed[attr];
  258. delete this._pending[attr];
  259. }
  260. }
  261. // Fire the `"change"` events.
  262. if (!options.silent) this.change(options);
  263. return this;
  264. },
  265. // Remove an attribute from the model, firing `"change"` unless you choose
  266. // to silence it. `unset` is a noop if the attribute doesn't exist.
  267. unset: function(attr, options) {
  268. (options || (options = {})).unset = true;
  269. return this.set(attr, null, options);
  270. },
  271. // Clear all attributes on the model, firing `"change"` unless you choose
  272. // to silence it.
  273. clear: function(options) {
  274. (options || (options = {})).unset = true;
  275. return this.set(_.clone(this.attributes), options);
  276. },
  277. // Fetch the model from the server. If the server's representation of the
  278. // model differs from its current attributes, they will be overriden,
  279. // triggering a `"change"` event.
  280. fetch: function(options) {
  281. options = options ? _.clone(options) : {};
  282. var model = this;
  283. var success = options.success;
  284. options.success = function(resp, status, xhr) {
  285. if (!model.set(model.parse(resp, xhr), options)) return false;
  286. if (success) success(model, resp);
  287. };
  288. options.error = Backbone.wrapError(options.error, model, options);
  289. return (this.sync || Backbone.sync).call(this, 'read', this, options);
  290. },
  291. // Set a hash of model attributes, and sync the model to the server.
  292. // If the server returns an attributes hash that differs, the model's
  293. // state will be `set` again.
  294. save: function(key, value, options) {
  295. var attrs, current;
  296. // Handle both `("key", value)` and `({key: value})` -style calls.
  297. if (_.isObject(key) || key == null) {
  298. attrs = key;
  299. options = value;
  300. } else {
  301. attrs = {};
  302. attrs[key] = value;
  303. }
  304. options = options ? _.clone(options) : {};
  305. // If we're "wait"-ing to set changed attributes, validate early.
  306. if (options.wait) {
  307. if (!this._validate(attrs, options)) return false;
  308. current = _.clone(this.attributes);
  309. }
  310. // Regular saves `set` attributes before persisting to the server.
  311. var silentOptions = _.extend({}, options, {silent: true});
  312. if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
  313. return false;
  314. }
  315. // After a successful server-side save, the client is (optionally)
  316. // updated with the server-side state.
  317. var model = this;
  318. var success = options.success;
  319. options.success = function(resp, status, xhr) {
  320. var serverAttrs = model.parse(resp, xhr);
  321. if (options.wait) {
  322. delete options.wait;
  323. serverAttrs = _.extend(attrs || {}, serverAttrs);
  324. }
  325. if (!model.set(serverAttrs, options)) return false;
  326. if (success) {
  327. success(model, resp);
  328. } else {
  329. model.trigger('sync', model, resp, options);
  330. }
  331. };
  332. // Finish configuring and sending the Ajax request.
  333. options.error = Backbone.wrapError(options.error, model, options);
  334. var method = this.isNew() ? 'create' : 'update';
  335. var xhr = (this.sync || Backbone.sync).call(this, method, this, options);
  336. if (options.wait) this.set(current, silentOptions);
  337. return xhr;
  338. },
  339. // Destroy this model on the server if it was already persisted.
  340. // Optimistically removes the model from its collection, if it has one.
  341. // If `wait: true` is passed, waits for the server to respond before removal.
  342. destroy: function(options) {
  343. options = options ? _.clone(options) : {};
  344. var model = this;
  345. var success = options.success;
  346. var triggerDestroy = function() {
  347. model.trigger('destroy', model, model.collection, options);
  348. };
  349. if (this.isNew()) {
  350. triggerDestroy();
  351. return false;
  352. }
  353. options.success = function(resp) {
  354. if (options.wait) triggerDestroy();
  355. if (success) {
  356. success(model, resp);
  357. } else {
  358. model.trigger('sync', model, resp, options);
  359. }
  360. };
  361. options.error = Backbone.wrapError(options.error, model, options);
  362. var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options);
  363. if (!options.wait) triggerDestroy();
  364. return xhr;
  365. },
  366. // Default URL for the model's representation on the server -- if you're
  367. // using Backbone's restful methods, override this to change the endpoint
  368. // that will be called.
  369. url: function() {
  370. var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError();
  371. if (this.isNew()) return base;
  372. return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
  373. },
  374. // **parse** converts a response into the hash of attributes to be `set` on
  375. // the model. The default implementation is just to pass the response along.
  376. parse: function(resp, xhr) {
  377. return resp;
  378. },
  379. // Create a new model with identical attributes to this one.
  380. clone: function() {
  381. return new this.constructor(this.attributes);
  382. },
  383. // A model is new if it has never been saved to the server, and lacks an id.
  384. isNew: function() {
  385. return this.id == null;
  386. },
  387. // Call this method to manually fire a `"change"` event for this model and
  388. // a `"change:attribute"` event for each changed attribute.
  389. // Calling this will cause all objects observing the model to update.
  390. change: function(options) {
  391. options || (options = {});
  392. var changing = this._changing;
  393. this._changing = true;
  394. // Silent changes become pending changes.
  395. for (var attr in this._silent) this._pending[attr] = true;
  396. // Silent changes are triggered.
  397. var changes = _.extend({}, options.changes, this._silent);
  398. this._silent = {};
  399. for (var attr in changes) {
  400. this.trigger('change:' + attr, this, this.get(attr), options);
  401. }
  402. if (changing) return this;
  403. // Continue firing `"change"` events while there are pending changes.
  404. while (!_.isEmpty(this._pending)) {
  405. this._pending = {};
  406. this.trigger('change', this, options);
  407. // Pending and silent changes still remain.
  408. for (var attr in this.changed) {
  409. if (this._pending[attr] || this._silent[attr]) continue;
  410. delete this.changed[attr];
  411. }
  412. this._previousAttributes = _.clone(this.attributes);
  413. }
  414. this._changing = false;
  415. return this;
  416. },
  417. // Determine if the model has changed since the last `"change"` event.
  418. // If you specify an attribute name, determine if that attribute has changed.
  419. hasChanged: function(attr) {
  420. if (!arguments.length) return !_.isEmpty(this.changed);
  421. return _.has(this.changed, attr);
  422. },
  423. // Return an object containing all the attributes that have changed, or
  424. // false if there are no changed attributes. Useful for determining what
  425. // parts of a view need to be updated and/or what attributes need to be
  426. // persisted to the server. Unset attributes will be set to undefined.
  427. // You can also pass an attributes object to diff against the model,
  428. // determining if there *would be* a change.
  429. changedAttributes: function(diff) {
  430. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  431. var val, changed = false, old = this._previousAttributes;
  432. for (var attr in diff) {
  433. if (_.isEqual(old[attr], (val = diff[attr]))) continue;
  434. (changed || (changed = {}))[attr] = val;
  435. }
  436. return changed;
  437. },
  438. // Get the previous value of an attribute, recorded at the time the last
  439. // `"change"` event was fired.
  440. previous: function(attr) {
  441. if (!arguments.length || !this._previousAttributes) return null;
  442. return this._previousAttributes[attr];
  443. },
  444. // Get all of the attributes of the model at the time of the previous
  445. // `"change"` event.
  446. previousAttributes: function() {
  447. return _.clone(this._previousAttributes);
  448. },
  449. // Check if the model is currently in a valid state. It's only possible to
  450. // get into an *invalid* state if you're using silent changes.
  451. isValid: function() {
  452. return !this.validate(this.attributes);
  453. },
  454. // Run validation against the next complete set of model attributes,
  455. // returning `true` if all is well. If a specific `error` callback has
  456. // been passed, call that instead of firing the general `"error"` event.
  457. _validate: function(attrs, options) {
  458. if (options.silent || !this.validate) return true;
  459. attrs = _.extend({}, this.attributes, attrs);
  460. var error = this.validate(attrs, options);
  461. if (!error) return true;
  462. if (options && options.error) {
  463. options.error(this, error, options);
  464. } else {
  465. this.trigger('error', this, error, options);
  466. }
  467. return false;
  468. }
  469. });
  470. // Backbone.Collection
  471. // -------------------
  472. // Provides a standard collection class for our sets of models, ordered
  473. // or unordered. If a `comparator` is specified, the Collection will maintain
  474. // its models in sort order, as they're added and removed.
  475. var Collection = Backbone.Collection = function(models, options) {
  476. options || (options = {});
  477. if (options.model) this.model = options.model;
  478. if (options.comparator) this.comparator = options.comparator;
  479. this._reset();
  480. this.initialize.apply(this, arguments);
  481. if (models) this.reset(models, {silent: true, parse: options.parse});
  482. };
  483. // Define the Collection's inheritable methods.
  484. _.extend(Collection.prototype, Events, {
  485. // The default model for a collection is just a **Backbone.Model**.
  486. // This should be overridden in most cases.
  487. model: Model,
  488. // Initialize is an empty function by default. Override it with your own
  489. // initialization logic.
  490. initialize: function(){},
  491. // The JSON representation of a Collection is an array of the
  492. // models' attributes.
  493. toJSON: function(options) {
  494. return this.map(function(model){ return model.toJSON(options); });
  495. },
  496. // Add a model, or list of models to the set. Pass **silent** to avoid
  497. // firing the `add` event for every new model.
  498. add: function(models, options) {
  499. var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
  500. options || (options = {});
  501. models = _.isArray(models) ? models.slice() : [models];
  502. // Begin by turning bare objects into model references, and preventing
  503. // invalid models or duplicate models from being added.
  504. for (i = 0, length = models.length; i < length; i++) {
  505. if (!(model = models[i] = this._prepareModel(models[i], options))) {
  506. throw new Error("Can't add an invalid model to a collection");
  507. }
  508. cid = model.cid;
  509. id = model.id;
  510. if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
  511. dups.push(i);
  512. continue;
  513. }
  514. cids[cid] = ids[id] = model;
  515. }
  516. // Remove duplicates.
  517. i = dups.length;
  518. while (i--) {
  519. models.splice(dups[i], 1);
  520. }
  521. // Listen to added models' events, and index models for lookup by
  522. // `id` and by `cid`.
  523. for (i = 0, length = models.length; i < length; i++) {
  524. (model = models[i]).on('all', this._onModelEvent, this);
  525. this._byCid[model.cid] = model;
  526. if (model.id != null) this._byId[model.id] = model;
  527. }
  528. // Insert models into the collection, re-sorting if needed, and triggering
  529. // `add` events unless silenced.
  530. this.length += length;
  531. index = options.at != null ? options.at : this.models.length;
  532. splice.apply(this.models, [index, 0].concat(models));
  533. if (this.comparator) this.sort({silent: true});
  534. if (options.silent) return this;
  535. for (i = 0, length = this.models.length; i < length; i++) {
  536. if (!cids[(model = this.models[i]).cid]) continue;
  537. options.index = i;
  538. model.trigger('add', model, this, options);
  539. }
  540. return this;
  541. },
  542. // Remove a model, or a list of models from the set. Pass silent to avoid
  543. // firing the `remove` event for every model removed.
  544. remove: function(models, options) {
  545. var i, l, index, model;
  546. options || (options = {});
  547. models = _.isArray(models) ? models.slice() : [models];
  548. for (i = 0, l = models.length; i < l; i++) {
  549. model = this.getByCid(models[i]) || this.get(models[i]);
  550. if (!model) continue;
  551. delete this._byId[model.id];
  552. delete this._byCid[model.cid];
  553. index = this.indexOf(model);
  554. this.models.splice(index, 1);
  555. this.length--;
  556. if (!options.silent) {
  557. options.index = index;
  558. model.trigger('remove', model, this, options);
  559. }
  560. this._removeReference(model);
  561. }
  562. return this;
  563. },
  564. // Add a model to the end of the collection.
  565. push: function(model, options) {
  566. model = this._prepareModel(model, options);
  567. this.add(model, options);
  568. return model;
  569. },
  570. // Remove a model from the end of the collection.
  571. pop: function(options) {
  572. var model = this.at(this.length - 1);
  573. this.remove(model, options);
  574. return model;
  575. },
  576. // Add a model to the beginning of the collection.
  577. unshift: function(model, options) {
  578. model = this._prepareModel(model, options);
  579. this.add(model, _.extend({at: 0}, options));
  580. return model;
  581. },
  582. // Remove a model from the beginning of the collection.
  583. shift: function(options) {
  584. var model = this.at(0);
  585. this.remove(model, options);
  586. return model;
  587. },
  588. // Get a model from the set by id.
  589. get: function(id) {
  590. if (id == null) return void 0;
  591. return this._byId[id.id != null ? id.id : id];
  592. },
  593. // Get a model from the set by client id.
  594. getByCid: function(cid) {
  595. return cid && this._byCid[cid.cid || cid];
  596. },
  597. // Get the model at the given index.
  598. at: function(index) {
  599. return this.models[index];
  600. },
  601. // Return models with matching attributes. Useful for simple cases of `filter`.
  602. where: function(attrs) {
  603. if (_.isEmpty(attrs)) return [];
  604. return this.filter(function(model) {
  605. for (var key in attrs) {
  606. if (attrs[key] !== model.get(key)) return false;
  607. }
  608. return true;
  609. });
  610. },
  611. // Force the collection to re-sort itself. You don't need to call this under
  612. // normal circumstances, as the set will maintain sort order as each item
  613. // is added.
  614. sort: function(options) {
  615. options || (options = {});
  616. if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
  617. var boundComparator = _.bind(this.comparator, this);
  618. if (this.comparator.length == 1) {
  619. this.models = this.sortBy(boundComparator);
  620. } else {
  621. this.models.sort(boundComparator);
  622. }
  623. if (!options.silent) this.trigger('reset', this, options);
  624. return this;
  625. },
  626. // Pluck an attribute from each model in the collection.
  627. pluck: function(attr) {
  628. return _.map(this.models, function(model){ return model.get(attr); });
  629. },
  630. // When you have more items than you want to add or remove individually,
  631. // you can reset the entire set with a new list of models, without firing
  632. // any `add` or `remove` events. Fires `reset` when finished.
  633. reset: function(models, options) {
  634. models || (models = []);
  635. options || (options = {});
  636. for (var i = 0, l = this.models.length; i < l; i++) {
  637. this._removeReference(this.models[i]);
  638. }
  639. this._reset();
  640. this.add(models, _.extend({silent: true}, options));
  641. if (!options.silent) this.trigger('reset', this, options);
  642. return this;
  643. },
  644. // Fetch the default set of models for this collection, resetting the
  645. // collection when they arrive. If `add: true` is passed, appends the
  646. // models to the collection instead of resetting.
  647. fetch: function(options) {
  648. options = options ? _.clone(options) : {};
  649. if (options.parse === undefined) options.parse = true;
  650. var collection = this;
  651. var success = options.success;
  652. options.success = function(resp, status, xhr) {
  653. collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
  654. if (success) success(collection, resp);
  655. };
  656. options.error = Backbone.wrapError(options.error, collection, options);
  657. return (this.sync || Backbone.sync).call(this, 'read', this, options);
  658. },
  659. // Create a new instance of a model in this collection. Add the model to the
  660. // collection immediately, unless `wait: true` is passed, in which case we
  661. // wait for the server to agree.
  662. create: function(model, options) {
  663. var coll = this;
  664. options = options ? _.clone(options) : {};
  665. model = this._prepareModel(model, options);
  666. if (!model) return false;
  667. if (!options.wait) coll.add(model, options);
  668. var success = options.success;
  669. options.success = function(nextModel, resp, xhr) {
  670. if (options.wait) coll.add(nextModel, options);
  671. if (success) {
  672. success(nextModel, resp);
  673. } else {
  674. nextModel.trigger('sync', model, resp, options);
  675. }
  676. };
  677. model.save(null, options);
  678. return model;
  679. },
  680. // **parse** converts a response into a list of models to be added to the
  681. // collection. The default implementation is just to pass it through.
  682. parse: function(resp, xhr) {
  683. return resp;
  684. },
  685. // Proxy to _'s chain. Can't be proxied the same way the rest of the
  686. // underscore methods are proxied because it relies on the underscore
  687. // constructor.
  688. chain: function () {
  689. return _(this.models).chain();
  690. },
  691. // Reset all internal state. Called when the collection is reset.
  692. _reset: function(options) {
  693. this.length = 0;
  694. this.models = [];
  695. this._byId = {};
  696. this._byCid = {};
  697. },
  698. // Prepare a model or hash of attributes to be added to this collection.
  699. _prepareModel: function(model, options) {
  700. options || (options = {});
  701. if (!(model instanceof Model)) {
  702. var attrs = model;
  703. options.collection = this;
  704. model = new this.model(attrs, options);
  705. if (!model._validate(model.attributes, options)) model = false;
  706. } else if (!model.collection) {
  707. model.collection = this;
  708. }
  709. return model;
  710. },
  711. // Internal method to remove a model's ties to a collection.
  712. _removeReference: function(model) {
  713. if (this == model.collection) {
  714. delete model.collection;
  715. }
  716. model.off('all', this._onModelEvent, this);
  717. },
  718. // Internal method called every time a model in the set fires an event.
  719. // Sets need to update their indexes when models change ids. All other
  720. // events simply proxy through. "add" and "remove" events that originate
  721. // in other collections are ignored.
  722. _onModelEvent: function(event, model, collection, options) {
  723. if ((event == 'add' || event == 'remove') && collection != this) return;
  724. if (event == 'destroy') {
  725. this.remove(model, options);
  726. }
  727. if (model && event === 'change:' + model.idAttribute) {
  728. delete this._byId[model.previous(model.idAttribute)];
  729. this._byId[model.id] = model;
  730. }
  731. this.trigger.apply(this, arguments);
  732. }
  733. });
  734. // Underscore methods that we want to implement on the Collection.
  735. var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
  736. 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
  737. 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
  738. 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
  739. 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
  740. // Mix in each Underscore method as a proxy to `Collection#models`.
  741. _.each(methods, function(method) {
  742. Collection.prototype[method] = function() {
  743. return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
  744. };
  745. });
  746. // Backbone.Router
  747. // -------------------
  748. // Routers map faux-URLs to actions, and fire events when routes are
  749. // matched. Creating a new one sets its `routes` hash, if not set statically.
  750. var Router = Backbone.Router = function(options) {
  751. options || (options = {});
  752. if (options.routes) this.routes = options.routes;
  753. this._bindRoutes();
  754. this.initialize.apply(this, arguments);
  755. };
  756. // Cached regular expressions for matching named param parts and splatted
  757. // parts of route strings.
  758. var namedParam = /:\w+/g;
  759. var splatParam = /\*\w+/g;
  760. var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
  761. // Set up all inheritable **Backbone.Router** properties and methods.
  762. _.extend(Router.prototype, Events, {
  763. // Initialize is an empty function by default. Override it with your own
  764. // initialization logic.
  765. initialize: function(){},
  766. // Manually bind a single named route to a callback. For example:
  767. //
  768. // this.route('search/:query/p:num', 'search', function(query, num) {
  769. // ...
  770. // });
  771. //
  772. route: function(route, name, callback) {
  773. Backbone.history || (Backbone.history = new History);
  774. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  775. if (!callback) callback = this[name];
  776. Backbone.history.route(route, _.bind(function(fragment) {
  777. var args = this._extractParameters(route, fragment);
  778. callback && callback.apply(this, args);
  779. this.trigger.apply(this, ['route:' + name].concat(args));
  780. Backbone.history.trigger('route', this, name, args);
  781. }, this));
  782. return this;
  783. },
  784. // Simple proxy to `Backbone.history` to save a fragment into the history.
  785. navigate: function(fragment, options) {
  786. Backbone.history.navigate(fragment, options);
  787. },
  788. // Bind all defined routes to `Backbone.history`. We have to reverse the
  789. // order of the routes here to support behavior where the most general
  790. // routes can be defined at the bottom of the route map.
  791. _bindRoutes: function() {
  792. if (!this.routes) return;
  793. var routes = [];
  794. for (var route in this.routes) {
  795. routes.unshift([route, this.routes[route]]);
  796. }
  797. for (var i = 0, l = routes.length; i < l; i++) {
  798. this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
  799. }
  800. },
  801. // Convert a route string into a regular expression, suitable for matching
  802. // against the current location hash.
  803. _routeToRegExp: function(route) {
  804. route = route.replace(escapeRegExp, '\\$&')
  805. .replace(namedParam, '([^\/]+)')
  806. .replace(splatParam, '(.*?)');
  807. return new RegExp('^' + route + '$');
  808. },
  809. // Given a route, and a URL fragment that it matches, return the array of
  810. // extracted parameters.
  811. _extractParameters: function(route, fragment) {
  812. return route.exec(fragment).slice(1);
  813. }
  814. });
  815. // Backbone.History
  816. // ----------------
  817. // Handles cross-browser history management, based on URL fragments. If the
  818. // browser does not support `onhashchange`, falls back to polling.
  819. var History = Backbone.History = function() {
  820. this.handlers = [];
  821. _.bindAll(this, 'checkUrl');
  822. };
  823. // Cached regex for cleaning leading hashes and slashes .
  824. var routeStripper = /^[#\/]/;
  825. // Cached regex for detecting MSIE.
  826. var isExplorer = /msie [\w.]+/;
  827. // Has the history handling already been started?
  828. History.started = false;
  829. // Set up all inheritable **Backbone.History** properties and methods.
  830. _.extend(History.prototype, Events, {
  831. // The default interval to poll for hash changes, if necessary, is
  832. // twenty times a second.
  833. interval: 50,
  834. // Gets the true hash value. Cannot use location.hash directly due to bug
  835. // in Firefox where location.hash will always be decoded.
  836. getHash: function(windowOverride) {
  837. var loc = windowOverride ? windowOverride.location : window.location;
  838. var match = loc.href.match(/#(.*)$/);
  839. return match ? match[1] : '';
  840. },
  841. // Get the cross-browser normalized URL fragment, either from the URL,
  842. // the hash, or the override.
  843. getFragment: function(fragment, forcePushState) {
  844. if (fragment == null) {
  845. if (this._hasPushState || forcePushState) {
  846. fragment = window.location.pathname;
  847. var search = window.location.search;
  848. if (search) fragment += search;
  849. } else {
  850. fragment = this.getHash();
  851. }
  852. }
  853. if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
  854. return fragment.replace(routeStripper, '');
  855. },
  856. // Start the hash change handling, returning `true` if the current URL matches
  857. // an existing route, and `false` otherwise.
  858. start: function(options) {
  859. if (History.started) throw new Error("Backbone.history has already been started");
  860. History.started = true;
  861. // Figure out the initial configuration. Do we need an iframe?
  862. // Is pushState desired ... is it available?
  863. this.options = _.extend({}, {root: '/'}, this.options, options);
  864. this._wantsHashChange = this.options.hashChange !== false;
  865. this._wantsPushState = !!this.options.pushState;
  866. this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);
  867. var fragment = this.getFragment();
  868. var docMode = document.documentMode;
  869. var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
  870. if (oldIE) {
  871. this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  872. this.navigate(fragment);
  873. }
  874. // Depending on whether we're using pushState or hashes, and whether
  875. // 'onhashchange' is supported, determine how we check the URL state.
  876. if (this._hasPushState) {
  877. $(window).bind('popstate', this.checkUrl);
  878. } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
  879. $(window).bind('hashchange', this.checkUrl);
  880. } else if (this._wantsHashChange) {
  881. this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
  882. }
  883. // Determine if we need to change the base url, for a pushState link
  884. // opened by a non-pushState browser.
  885. this.fragment = fragment;
  886. var loc = window.location;
  887. var atRoot = loc.pathname == this.options.root;
  888. // If we've started off with a route from a `pushState`-enabled browser,
  889. // but we're currently in a browser that doesn't support it...
  890. if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
  891. this.fragment = this.getFragment(null, true);
  892. window.location.replace(this.options.root + '#' + this.fragment);
  893. // Return immediately as browser will do redirect to new url
  894. return true;
  895. // Or if we've started out with a hash-based route, but we're currently
  896. // in a browser where it could be `pushState`-based instead...
  897. } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
  898. this.fragment = this.getHash().replace(routeStripper, '');
  899. window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
  900. }
  901. if (!this.options.silent) {
  902. return this.loadUrl();
  903. }
  904. },
  905. // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
  906. // but possibly useful for unit testing Routers.
  907. stop: function() {
  908. $(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
  909. clearInterval(this._checkUrlInterval);
  910. History.started = false;
  911. },
  912. // Add a route to be tested when the fragment changes. Routes added later
  913. // may override previous routes.
  914. route: function(route, callback) {
  915. this.handlers.unshift({route: route, callback: callback});
  916. },
  917. // Checks the current URL to see if it has changed, and if it has,
  918. // calls `loadUrl`, normalizing across the hidden iframe.
  919. checkUrl: function(e) {
  920. var current = this.getFragment();
  921. if (current == this.fragment && this.iframe) current = this.getFragment(this.getHash(this.iframe));
  922. if (current == this.fragment) return false;
  923. if (this.iframe) this.navigate(current);
  924. this.loadUrl() || this.loadUrl(this.getHash());
  925. },
  926. // Attempt to load the current URL fragment. If a route succeeds with a
  927. // match, returns `true`. If no defined routes matches the fragment,
  928. // returns `false`.
  929. loadUrl: function(fragmentOverride) {
  930. var fragment = this.fragment = this.getFragment(fragmentOverride);
  931. var matched = _.any(this.handlers, function(handler) {
  932. if (handler.route.test(fragment)) {
  933. handler.callback(fragment);
  934. return true;
  935. }
  936. });
  937. return matched;
  938. },
  939. // Save a fragment into the hash history, or replace the URL state if the
  940. // 'replace' option is passed. You are responsible for properly URL-encoding
  941. // the fragment in advance.
  942. //
  943. // The options object can contain `trigger: true` if you wish to have the
  944. // route callback be fired (not usually desirable), or `replace: true`, if
  945. // you wish to modify the current URL without adding an entry to the history.
  946. navigate: function(fragment, options) {
  947. if (!History.started) return false;
  948. if (!options || options === true) options = {trigger: options};
  949. var frag = (fragment || '').replace(routeStripper, '');
  950. if (this.fragment == frag) return;
  951. // If pushState is available, we use it to set the fragment as a real URL.
  952. if (this._hasPushState) {
  953. if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
  954. this.fragment = frag;
  955. window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);
  956. // If hash changes haven't been explicitly disabled, update the hash
  957. // fragment to store history.
  958. } else if (this._wantsHashChange) {
  959. this.fragment = frag;
  960. this._updateHash(window.location, frag, options.replace);
  961. if (this.iframe && (frag != this.getFragment(this.getHash(this.iframe)))) {
  962. // Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
  963. // When replace is true, we don't want this.
  964. if(!options.replace) this.iframe.document.open().close();
  965. this._updateHash(this.iframe.location, frag, options.replace);
  966. }
  967. // If you've told us that you explicitly don't want fallback hashchange-
  968. // based history, then `navigate` becomes a page refresh.
  969. } else {
  970. window.location.assign(this.options.root + fragment);
  971. }
  972. if (options.trigger) this.loadUrl(fragment);
  973. },
  974. // Update the hash location, either replacing the current entry, or adding
  975. // a new one to the browser history.
  976. _updateHash: function(location, fragment, replace) {
  977. if (replace) {
  978. location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
  979. } else {
  980. location.hash = fragment;
  981. }
  982. }
  983. });
  984. // Backbone.View
  985. // -------------
  986. // Creating a Backbone.View creates its initial element outside of the DOM,
  987. // if an existing element is not provided...
  988. var View = Backbone.View = function(options) {
  989. this.cid = _.uniqueId('view');
  990. this._configure(options || {});
  991. this._ensureElement();
  992. this.initialize.apply(this, arguments);
  993. this.delegateEvents();
  994. };
  995. // Cached regex to split keys for `delegate`.
  996. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  997. // List of view options to be merged as properties.
  998. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
  999. // Set up all inheritable **Backbone.View** properties and methods.
  1000. _.extend(View.prototype, Events, {
  1001. // The default `tagName` of a View's element is `"div"`.
  1002. tagName: 'div',
  1003. // jQuery delegate for element lookup, scoped to DOM elements within the
  1004. // current view. This should be prefered to global lookups where possible.
  1005. $: function(selector) {
  1006. return this.$el.find(selector);
  1007. },
  1008. // Initialize is an empty function by default. Override it with your own
  1009. // initialization logic.
  1010. initialize: function(){},
  1011. // **render** is the core function that your view should override, in order
  1012. // to populate its element (`this.el`), with the appropriate HTML. The
  1013. // convention is for **render** to always return `this`.
  1014. render: function() {
  1015. return this;
  1016. },
  1017. // Remove this view from the DOM. Note that the view isn't present in the
  1018. // DOM by default, so calling this method may be a no-op.
  1019. remove: function() {
  1020. this.$el.remove();
  1021. return this;
  1022. },
  1023. // For small amounts of DOM Elements, where a full-blown template isn't
  1024. // needed, use **make** to manufacture elements, one at a time.
  1025. //
  1026. // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
  1027. //
  1028. make: function(tagName, attributes, content) {
  1029. var el = document.createElement(tagName);
  1030. if (attributes) $(el).attr(attributes);
  1031. if (content != null) $(el).html(content);
  1032. return el;
  1033. },
  1034. // Change the view's element (`this.el` property), including event
  1035. // re-delegation.
  1036. setElement: function(element, delegate) {
  1037. if (this.$el) this.undelegateEvents();
  1038. this.$el = (element instanceof $) ? element : $(element);
  1039. this.el = this.$el[0];
  1040. if (delegate !== false) this.delegateEvents();
  1041. return this;
  1042. },
  1043. // Set callbacks, where `this.events` is a hash of
  1044. //
  1045. // *{"event selector": "callback"}*
  1046. //
  1047. // {
  1048. // 'mousedown .title': 'edit',
  1049. // 'click .button': 'save'
  1050. // 'click .open': function(e) { ... }
  1051. // }
  1052. //
  1053. // pairs. Callbacks will be bound to the view, with `this` set properly.
  1054. // Uses event delegation for efficiency.
  1055. // Omitting the selector binds the event to `this.el`.
  1056. // This only works for delegate-able events: not `focus`, `blur`, and
  1057. // not `change`, `submit`, and `reset` in Internet Explorer.
  1058. delegateEvents: function(events) {
  1059. if (!(events || (events = getValue(this, 'events')))) return;
  1060. this.undelegateEvents();
  1061. for (var key in events) {
  1062. var method = events[key];
  1063. if (!_.isFunction(method)) method = this[events[key]];
  1064. if (!method) throw new Error('Method "' + events[key] + '" does not exist');
  1065. var match = key.match(delegateEventSplitter);
  1066. var eventName = match[1], selector = match[2];
  1067. method = _.bind(method, this);
  1068. eventName += '.delegateEvents' + this.cid;
  1069. if (selector === '') {
  1070. this.$el.bind(eventName, method);
  1071. } else {
  1072. this.$el.delegate(selector, eventName, method);
  1073. }
  1074. }
  1075. },
  1076. // Clears all callbacks previously bound to the view with `delegateEvents`.
  1077. // You usually don't need to use this, but may wish to if you have multiple
  1078. // Backbone views attached to the same DOM element.
  1079. undelegateEvents: function() {
  1080. this.$el.unbind('.delegateEvents' + this.cid);
  1081. },
  1082. // Performs the initial configuration of a View with a set of options.
  1083. // Keys with special meaning *(model, collection, id, className)*, are
  1084. // attached directly to the view.
  1085. _configure: function(options) {
  1086. if (this.options) options = _.extend({}, this.options, options);
  1087. for (var i = 0, l = viewOptions.length; i < l; i++) {
  1088. var attr = viewOptions[i];
  1089. if (options[attr]) this[attr] = options[attr];
  1090. }
  1091. this.options = options;
  1092. },
  1093. // Ensure that the View has a DOM element to render into.
  1094. // If `this.el` is a string, pass it through `$()`, take the first
  1095. // matching element, and re-assign it to `el`. Otherwise, create
  1096. // an element from the `id`, `className` and `tagName` properties.
  1097. _ensureElement: function() {
  1098. if (!this.el) {
  1099. var attrs = getValue(this, 'attributes') || {};
  1100. if (this.id) attrs.id = this.id;
  1101. if (this.className) attrs['class'] = this.className;
  1102. this.setElement(this.make(this.tagName, attrs), false);
  1103. } else {
  1104. this.setElement(this.el, false);
  1105. }
  1106. }
  1107. });
  1108. // The self-propagating extend function that Backbone classes use.
  1109. var extend = function (protoProps, classProps) {
  1110. var child = inherits(this, protoProps, classProps);
  1111. child.extend = this.extend;
  1112. return child;
  1113. };
  1114. // Set up inheritance for the model, collection, and view.
  1115. Model.extend = Collection.extend = Router.extend = View.extend = extend;
  1116. // Backbone.sync
  1117. // -------------
  1118. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  1119. var methodMap = {
  1120. 'create': 'POST',
  1121. 'update': 'PUT',
  1122. 'delete': 'DELETE',
  1123. 'read': 'GET'
  1124. };
  1125. // Override this function to change the manner in which Backbone persists
  1126. // models to the server. You will be passed the type of request, and the
  1127. // model in question. By default, makes a RESTful Ajax request
  1128. // to the model's `url()`. Some possible customizations could be:
  1129. //
  1130. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  1131. // * Send up the models as XML instead of JSON.
  1132. // * Persist models via WebSockets instead of Ajax.
  1133. //
  1134. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  1135. // as `POST`, with a `_method` parameter containing the true HTTP method,
  1136. // as well as all requests with the body as `application/x-www-form-urlencoded`
  1137. // instead of `application/json` with the model in a param named `model`.
  1138. // Useful when interfacing with server-side languages like **PHP** that make
  1139. // it difficult to read the body of `PUT` requests.
  1140. Backbone.sync = function(method, model, options) {
  1141. var type = methodMap[method];
  1142. // Default options, unless specified.
  1143. options || (options = {});
  1144. // Default JSON-request options.
  1145. var params = {type: type, dataType: 'json'};
  1146. // Ensure that we have a URL.
  1147. if (!options.url) {
  1148. params.url = getValue(model, 'url') || urlError();
  1149. }
  1150. // Ensure that we have the appropriate request data.
  1151. if (!options.data && model && (method == 'create' || method == 'update')) {
  1152. params.contentType = 'application/json';
  1153. params.data = JSON.stringify(model.toJSON());
  1154. }
  1155. // For older servers, emulate JSON by encoding the request into an HTML-form.
  1156. if (Backbone.emulateJSON) {
  1157. params.contentType = 'application/x-www-form-urlencoded';
  1158. params.data = params.data ? {model: params.data} : {};
  1159. }
  1160. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  1161. // And an `X-HTTP-Method-Override` header.
  1162. if (Backbone.emulateHTTP) {
  1163. if (type === 'PUT' || type === 'DELETE') {
  1164. if (Backbone.emulateJSON) params.data._method = type;
  1165. params.type = 'POST';
  1166. params.beforeSend = function(xhr) {
  1167. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  1168. };
  1169. }
  1170. }
  1171. // Don't process data on a non-GET request.
  1172. if (params.type !== 'GET' && !Backbone.emulateJSON) {
  1173. params.processData = false;
  1174. }
  1175. // Make the request, allowing the user to override any Ajax options.
  1176. return $.ajax(_.extend(params, options));
  1177. };
  1178. // Wrap an optional error callback with a fallback error event.
  1179. Backbone.wrapError = function(onError, originalModel, options) {
  1180. return function(model, resp) {
  1181. resp = model === originalModel ? resp : model;
  1182. if (onError) {
  1183. onError(originalModel, resp, options);
  1184. } else {
  1185. originalModel.trigger('error', originalModel, resp, options);
  1186. }
  1187. };
  1188. };
  1189. // Helpers
  1190. // -------
  1191. // Shared empty constructor function to aid in prototype-chain creation.
  1192. var ctor = function(){};
  1193. // Helper function to correctly set up the prototype chain, for subclasses.
  1194. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  1195. // class properties to be extended.
  1196. var inherits = function(parent, protoProps, staticProps) {
  1197. var child;
  1198. // The constructor function for the new subclass is either defined by you
  1199. // (the "constructor" property in your `extend` definition), or defaulted
  1200. // by us to simply call the parent's constructor.
  1201. if (protoProps && protoProps.hasOwnProperty('constructor')) {
  1202. child = protoProps.constructor;
  1203. } else {
  1204. child = function(){ parent.apply(this, arguments); };
  1205. }
  1206. // Inherit class (static) properties from parent.
  1207. _.extend(child, parent);
  1208. // Set the prototype chain to inherit from `parent`, without calling
  1209. // `parent`'s constructor function.
  1210. ctor.prototype = parent.prototype;
  1211. child.prototype = new ctor();
  1212. // Add prototype properties (instance properties) to the subclass,
  1213. // if supplied.
  1214. if (protoProps) _.extend(child.prototype, protoProps);
  1215. // Add static properties to the constructor function, if supplied.
  1216. if (staticProps) _.extend(child, staticProps);
  1217. // Correctly set child's `prototype.constructor`.
  1218. child.prototype.constructor = child;
  1219. // Set a convenience property in case the parent's prototype is needed later.
  1220. child.__super__ = parent.prototype;
  1221. return child;
  1222. };
  1223. // Helper function to get a value from a Backbone object as a property
  1224. // or as a function.
  1225. var getValue = function(object, prop) {
  1226. if (!(object && object[prop])) return null;
  1227. return _.isFunction(object[prop]) ? object[prop]() : object[prop];
  1228. };
  1229. // Throw an error when a URL is needed, and none is supplied.
  1230. var urlError = function() {
  1231. throw new Error('A "url" property or function must be specified');
  1232. };
  1233. return Backbone;
  1234. }));