PageRenderTime 57ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/backbonejs/0.9.2/backbone.js

http://github.com/thomasfr/requirified
JavaScript | 1412 lines | 846 code | 196 blank | 370 comment | 289 complexity | 2698f4b2f422e546808ae887ccaefa0b MD5 | raw file
Possible License(s): MIT, Apache-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file