PageRenderTime 78ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 1ms

/examples/todos/backbone.js

https://bitbucket.org/dlisboa/backbone
JavaScript | 1497 lines | 908 code | 215 blank | 374 comment | 315 complexity | b831b13a5a4874a78d684e6ad3bd9edd MD5 | raw file

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

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

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