PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/backbone.js

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

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