PageRenderTime 75ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/backbone.js

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