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

/examples/chatter2/chatter2/static/backbone.js

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