PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/nabe/util/init/blog/articles/backbone.js

http://github.com/mklabs/nabe
JavaScript | 1359 lines | 829 code | 173 blank | 357 comment | 289 complexity | b1db74e638aa4775f6eae7a5e69b9f34 MD5 | raw file

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

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

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