PageRenderTime 74ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/todos/backbone.js

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