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

/cfzwww/static/javascript/libs/backbone.js

https://bitbucket.org/uris77/cfz-www
JavaScript | 1498 lines | 909 code | 215 blank | 374 comment | 315 complexity | 70263c60223f9cf26a954b04010f93c1 MD5 | raw file

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

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

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