PageRenderTime 69ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/backbone.js

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