PageRenderTime 105ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 1ms

/fb_twitter_login/client/js/lib/backbone.js

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